Skip to content

Conditional Statements

Dictionary

A conditional statement is a Boolean expression that executes a piece of code based on the outcome of Boolean expressions.

There are 3 types of conditional statements:

  • if statement
  • if-else statement
  • if-elif-else statement

The if Statement

For a statement, if the condition holds True, execute the code to be executed. Otherwise, skip it and move on.

SYNTAX:

Info

Indentation plays an essential role in Python.

Statements with the same level of indentation belong to the same block of code. The convention of our indents must also be consistent throughout a block.

Let's see if conditions in action

1
2
3
4
5
6
7
num = 5

if (num<10):    # this condition is True
    print("The number is less than 10")

if (num>5):     # this condition is False
    print("The number is greater than 5")
Result
1
The number is less than 10

We can see, the print command inside the body of the if statement is indented to the right. Below you can find Indentation Error,

1
2
if (num>5):                           # this condition is False
print("The number is greater than 5") # this line will throw an error
Result
1
2
3
4
File "<stdin>", line 2
print("The number is greater than 5")
    ^
IndentationError: expected an indented block

We can also use logical operators in case we want the condition to satisfy more than 1 condition.

Tip

if statements act independently.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
num = 54

if num%2==0 and num%3==0:              # this condition holds true
    print("The number is multiple of by 2 and 3")

num = 100

if (num and (not(num & (num - 1)))):   # this condition holds false 
    print("The number is power of 2")

if (num%2!=1):                         # this condition holds True
    print(f"{num} is an even number.")
Result
1
2
The number is multiple of by 2 and 3
54 is an even number.

Nested if Statements

A cool feature is that there could be an if statement inside another!

Tip

Each nested if statement requires further indentation when using nested conditions.

if condition statements with the same indentation inside a scope act independently.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
bob_age = 64
riya_age = 23
alex_age = 96

if bob_age > riya_age:      # condition True
    print("Bob is older than Riya")
    if bob_age > alex_age:  # condition False
        print("Bob is older than Alex")

    print("The show is over.")
Result
1
2
Bob is older than Riya
The show is over.
  • Line number 5, condition holds True, so the interpreter goes into that block and executes 6th line statement.
  • Next 7th line statement condition holds False, therefore any statements under that condition will be skipped and the interpreter will move to line number 10 and execute it.

Do remember all the statements under a False condition block will be skipped.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
statement_one = "It’s important to be kind"
statement_two = ", as it will always be rewarded."
read_story = False  

if read_story:      # condition False
    print("Moral of the story is: ")
    print(statement_one)
    print(statement_two)

print("Read another story")
Result
1
Read another story

The above code will execute without an error, but as the condition is False, none of the statements under that block will get executed and the interpreter will jump to the next line where that block ends.

Using conditional statements we can edit the values of the variables.

1
2
3
4
5
6
7
8
num = 100

if num%2==0:            # condition holds True
    num -= 1            # num becomes 99
    new_num = num*2     # new_num becomes 198

print(num)
print(new_num)
Result
1
2
99
198

Bug

In the above code, we have assigned a new variable name new_num inside the if condition statement. This practice is not recommended. If the condition is false, you will get an error stating NameError: name 'new_num' is not defined as new_num was defined in the scope of if condition.

Make the if condition false and see it in action.

The if-else Statement

If we want to execute a different set of operations in case the if condition turns out to be False. We would use this type of statement.

SYNTAX:

Remember, the else keyword needs to be on the same indentation level as the if keyword.

Let's see a nested condition.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
bob_age = 64
riya_age = 23
alex_age = 96

if bob_age > riya_age:                    # condition True
    print("Bob is older than Riya")       
    if bob_age > alex_age:                # condition False
        print("Bob is older than Alex")   
    else:
        print("Bob is younger than Alex") 
else:                                     
    print("Bob is younger than Riya)
Result
1
2
Bob is older than Riya
Bob is younger than Alex

Tip

Do keep in mind that the else statement cannot exist on its own. Although there can be an if condition statement without an else condition.

The if-elif-else Statement

In programming, a problem can have multiple outcomes and not just True or False.

Here, elif stands for else if. If the first if condition expression is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed if mentioned.

SYNTAX:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
light = "Red"

if light == "Green":
    print("Go")

elif light == "Yellow":
    print("Slow Down")

elif light == "Red":
    print("Stop")

else:
    print("Incorrect light signal")
Result
1
Stop

Tip

An if-elif statement can exist on its own without an else block at the end. However, an elif cannot exist without an if statement preceding it.


In the next section, we will start with Functions.

Back to top