Technical Roadmap

Conditional Statements in Python

In life, at every point we have to take some decisions like Yes or No. Similarly, in programming we have to execute some decisions based on some conditions. To implement these decisions we use conditionals.

What are Conditional Statements ?

Statements that execute on the basis of some conditions are conditional statements.

There are three conditional statements in Python:

  • if
  • elif
  • else

1. If statement

The if statement executes only if the condition is "True".

For example: Your mother says if it rains don't go to school.
Condition: Is it raining?
If True: Don't go to school (the block inside if executes)

Syntax:

if condition:
    # statement if True

For example:

PYTHON
num=4
if num>0: 
  print(f"{num} is greater")

Output

4 is greater

Explanation: In the above code example we declare a variable num=4. In the next line we used if to check the condition: is num greater than 0. The condition is True so we execute the code block inside the if. Hence we got output as "4 is greater".

Let's take another example where num is less than zero. We will see how if works in this situation.

PYTHON
num=0
if num>0:
  print(f"{num} is greater" )
print("this is outside if")

Output

this is outside if

Explanation: Here the condition is False so the if block didn't execute and we skip it and move to the next line.

2. Elif statement

Sometimes we need to check multiple conditions, then we use the elif. The elif checks for multiple conditions. It is used with if.

Let's take the same example: if your mother says that if it rains stay home and if it's a holiday sleep more. Now you have 2 conditions. So we will use the elif. For the first condition we will use if and for any other we will keep on adding elif.

Condition 1: Is it raining?
Condition 2: Is it a holiday?

Syntax:

if condition1:
    # block 1
elif condition2:
    # block 2
    

For example:

PYTHON
num=4
if num>10:
  print(f"{num} is greater than 10")
elif num<10:
  print(f"{num} is less than 10")

Output

4 is less than 10

Explanation: Here we checked for two conditions: is num greater than 10 or less than 10. We can add more elif statements if we want. Here the elif block executes because the if condition returned False, but elif returned True.

3. Else statement

We have seen that both if and elif execute when the condition is "True". But what if the condition is "False"?

If your mother says if it rains don't go to school. But what if it doesn't rain? You will go.


Condition : Is it raining?
If True: Don't Go
If False: Go

Syntax:

if condition:
    # statement if True
else:
    # statement if False
    

For example:

PYTHON
num=4
if num>4:
  print(f"{num} is greater than 4")
if num<0:
  print(f"{num} is less than 4")
else:
  print(f"{num} is equal to 4")

Output

4 is equal to 4