python

Getting if...else


If statement

An "if statement" is used to written by if keyword.
Syntax:


if condition:
    statement()
Example:

M=144
N=169
      condition
if N>M:
    print("N is greater than M")
Output:

N is greter than M

In the above program, we use 2 variables M and N which are the part of if statement to test whether N is greater than M or not.
Here,N=169 and M=144 as we can see N is greater than M. Therefore the output is N is greter than M.



Elif statement

Basically elif in python is like else-if in C++. It says that if the current condition is not true then check the next condition.
The keyword used is elif for this.

Syntax:

if condition 1:
    statement(1)
elif condition 2:
    statement(2)
Example:

M=200
N=100

if N>M:
    print("N is greater than M")
elif M>N:
    print("M is greater than N")
    
Output:

M is greater than N

In the above program, we use 2 variables again M and N.But here the twist is about the condition. As you can see here first condition is not satisfied therefore it went for next condition i.e N>M and it is True.
Therefore, it prints M is greater than N.



Else statement

The else condition cover anything which cannot be covered by the previous conditions of if and elif. Syntax:

if condition 1:
    statement(1)
elif condition 2:
    statement(2)
else:
    statement(3)
    
Note: else does not contain any condition.
Example:

M=40
N=40

if N>M:
    print("N is greater than M")
elif M>N:
    print("M is greater than N")
else:
    print("M is equal to N")
    
Output:

M is equal to N

In the above program, both the previous conditon are not satisfied. Therefore the result is printed of else condition.

Indentation

Python depends on indentation(whitespace in the beginning of line) to define the scope.Therefore we have to give some whitespace as you can see in the above programs.


Flowchart of if,elif,else
flowchart of if,elif,else

M=90
N=100

if N>M:
print("N is greater than M")  #This will give you error