Introduction

Any program needs to be able to make decisions. When certain condition is met, certain action needs to be taken. To facilitate this, we need to use conditional statements. Basic syntax of conditional statement in Python looks like the following

1
2
3
4
5
6
if <condition>:
	# do something
elif <condition2>:
	# do something
else:
	# do something else

Here, if, elif and else are Python keywords to support conditional statement. Python will execute different code depending on the condition. For example,

1
2
3
age = 75
if age > 60:
	print("You are old")

In the code above, we have 75 as value of age and in the if condition we check whether age is greater than 60. If this condition is true then execute the print statement. Note the indentation of print statement. Python uses indentation to determine a block of code that it should execute when that condition is met. You can have more than one statements in a code-block but they should have same level of indentation. For example

1
2
3
4
5
age = 50
if age > 60:
	print("You are old")
	print("This will only print if age is greater than 60")
print("Program finished")

In the code above, the last print statement will execute no matter what the value of age is, since that line of code does not have same level of indentation as the statement print("You are old").

If you want to run a different code if your condition is not true then you can use else.

1
2
3
4
5
age = 50
if age > 60:
	print("You are old")
else:
	print("You are not old")

In the above program, it will print “You are old” if age is more than 60 otherwise it will print “You are not old”.

What if you have multiple conditions and you want to run different code for each condition? You can use elif .

1
2
3
4
5
6
7
age = 60
if age <= 19:
	print("Teen")
elif age <= 60:
	print("Adult")
else:
	print("Old")

The code above will print either “Teen” or “Adult” or “Old” depending on the value of age. You can have as many elifs you want.

To summarize, to use conditional statement you can use if statement. Using elif is optional and can be repeated as many times as you want. Using else is also optional but if you use it there can be only one else block.

You can also negate the condition and “join” multiple conditions using and and or keywords. For example

1
2
3
age = 20
if not age > 60:
	print("You are not old")

The if statement above can be read as: “If age is not greater than 60 then do the following”.

To use multiple conditions simply use and or or keywords.

1
2
3
4
5
age = 20
salary = 100000

if age < 30 and salary > 90000:
	print("You are doing quite good!")

The above statement can be read as: “If age is less than 30 and salary is greater than 90,000 then do the following”.

Truthy

So far our conditions evaluate to boolean values i.e. True or False. age < 19 returns either True or False depending on the value of age but you can have conditions that do not return actual boolean values. They can be “truthy” or “falsy”. Take a look at the code example below to see what Python considers to be “truthy” or “falsy”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
if 1:
    print("1 is truthy")

if not 0:
    print("0 is falsy")
    
age = 10
if age:
    print("any number except 0 is truthy")
    
empty_list = []
if empty_list:
    print("empty list is never truthy")
else:
    print("empty list is falsy")
    
list_with_values = ["a", "b"]
if list_with_values:
    print("non-empty list is truthy")
    
empty_dictionary = {}
if empty_dictionary:
    print("empty dictionary is never truthy")
else:
    print("empty dictionary is falsy")

    
none_value = None
if none_value:
    print("None is never truthy")
else:
    print("None is falsy")

The code above prints the following. Use this as a reference to remember what conditions you can use in if statements.

1
2
3
4
5
6
7
1 is truthy
0 is falsy
any number except 0 is truthy
empty list is falsy
non-empty list is truthy
empty dictionary is falsy
None is falsy    

How “truthy” can help? Let’s say you have a program to keep track of todos. And you want to print out the first todo in the list. But let’s assume that there are no todos filled out yet so the list is empty. If you simply write a code like below then Python will throw an exception.

1
2
todos = []
print(todos[0])
1
2
3
4
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(todos[0])
IndexError: list index out of range

Now, we have to make sure that before we print, there is at least one todo in our list. We can write something like this

1
2
3
todos = []
if len(todos) > 0:
	print(todos[0])

This code will not throw an error like above because we are telling Python to print the first todo only if “length of todos is greater than 0” or in other words there is at least one todo in the list. This is perfectly valid but we can also rewrite it as

1
2
3
todos = []
if todos:
	print(todos[0])

Remember that an empty list is “falsy” so the condition is not satisfied. Python will never execute the print statement if the list is empty.

I would definitely recommend using if len(todos) > 0 variant for beginners since it is more explicit but you will see the later variant in many places so don’t get confused!

Updated:

Comments