This tutorial shows how to write an if and else statement in Python with detailed examples.
Comparisons in if else in Python
The following table shows the notations used in Python to indicate the comparision between x and y.
Definitions | Python |
Equal | x==y |
Not equal | x!=y |
Less | x<y |
Less or Equal | x<=y |
greater | x>y |
greater or equal | x>=y |
Example 1: if statment in Python
The following shows an example with if only.
a=1
if a<2:
print("a is smaller than 2")
The following is the ouput.
a is smaller than 2
Example 2: if …else…statment in Python
a=1
if a>2:
print("a is greater than 2")
else:
print("a is smaller than 2")
The following is the output.
a is smaller than 2
Example 3: if …elif…else statement in Python
a=1
if a>2:
print("a is greater than 2")
elif a==2:
print("a is equal to 2")
else:
print("a is smaller than 2")
a is smaller than 2