How to Write If Else in Python

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.

DefinitionsPython
Equalx==y
Not equalx!=y
Lessx<y
Less or Equal x<=y
greaterx>y
greater or equalx>=y
Comparison in Python

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