Python by example

If Else in Python

The if keyword is used to create a conditional statement that executes a block of code if a condition is true.

x = 5
if x > 3:
    print("x is greater than 3")

The else keyword can be used to execute a block of code if the condition is false.

x = 2
if x > 3:
    print("x is greater than 3")
else:
    print("x is less than or equal to 3")

The elif keyword can be used to create multiple conditions in a single if statement.

x = 3
if x > 3:
    print("x is greater than 3")
elif x < 3:
    print("x is less than 3")
else:
    print("x is equal to 3")
Next example: Switch