Nested conditions in Python (6/100 Days of Python)

Martin Mirakyan
2 min readJan 7, 2023

--

Day 6 of the “100 Days of Python” blog post series covering nested conditions (if/else) and elif statements

In Python, it is possible to nest one conditional statement inside of another:

x = 10
y = 5

if x > y:
print('x is greater than y')
if x > 10:
print('x is also greater than 10')

In this example, the first if statement checks if x is greater than y. If this is True, then the second if statement is executed. This checks if x is greater than 10. If this is also True, then the string x is also greater than 10 is printed by the program.

You can nest conditional statements as deeply as you like, but be careful not to create overly complex code that is difficult to read and understand. The following, for instance, is very hard to read and maintain, and is usually considered an antipattern in software engineering:

if a > 1:
if b < 20:
if c == 'hello':
if d == 30:
print('Hello')
else:
if k == '80':
print('k is 80')
if a > 20:
print('World')
else:
print('!!')

elif Statements

Some blocks of Python code are pretty common — especially those that include some if statements inside else blocks:

if name == 'Bob':
print('Hey Bob!')
else:
if name == 'Alice':
print('How are you doing Alice?')
else:
if name == 'Anna':
print('Hello, Anna!!!')
else:
if name == 'Martin':
print('Hi, Martin')
else:
print('Wait! I don\'t not know you right?')
# We can have some more nesting here...

This code can be rewritten in a more elegant way using elif statements. elif statements are a shorthand for else ... if blocks (which we saw repeating in the code above). So, the new version of the same code can be:

if name == 'Bob':
print('Hey Bob!')
elif name == 'Alice':
print('How are you doing Alice?')
elif name == 'Anna':
print('Hello, Anna!!!')
elif name == 'Martin':
print('Hi, Martin')
else:
print('Wait! I don\'t not know you right?')

This code is shorter, less nested (it’s a good practice to avoid nesting), and more readable.

We can also have some more conditional statements inside elif blocks to execute a block of code if those conditions are met:

if name == 'Bob':
if age >= 18:
print('Welcome')
else:
print('You are not allowed')
elif name == 'Anna'):
if age >= 18 and homework_is_done:
print('Welcome')
else:
print('Sorry, not allowed')
else:
print('I\'m not sure if I know you...')

So, Python has 3 conditional statements — if, else, and elif which are used very frequently in real-world software engineering.

What’s next?

--

--