Python Basics #13 — if Statement
In this lesson we’ll cover the most fundamental control-flow statement in Python: the if statement.
An if statement has three kinds of blocks: if, elif, and else. Each block has a test expression and a body that runs when the test passes. If the test is True, the body runs. If False, the next elif test runs. If all tests are False, the else body runs.
A typical if statement looks like this:
if a == b:
print('first condition is true')
elif a == c:
print('second condition is true')
else:
print('none of the above conditions are true')To add more conditions, just add more elif blocks:
if a == b:
print('first condition is true')
elif a == c:
print('second condition is true')
elif a == d:
print('third condition is true')
elif a == e:
print('fourth condition is true')
elif a == f:
print('fifth condition is true')
else:
print('none of the conditions are true')Use an if statement to compare two numbers stored in a and b:
>>> a = 1
>>> b = 2Comparing two numbers, there are three possible cases:
a > b
a == b
a < bYou can handle all three cases with one if statement:
>>> if a > b:
... print('a > b')
... elif a == b:
... print('a == b')
... else:
... print('a < b')
...
a < bThe else branch runs and correctly prints that a is less than b.
A common mistake — this is not the right way to use if:
>>> if a > b:
... print('a > b')
...
>>> if a == b:
... print('a == b')
...
>>> if a < b:
... print('a < b')
...
a < bThe output is the same as the previous example, but this code has a problem. With elif, once a condition matches, the remaining tests below are skipped. But if you write three separate if statements like this, the program runs every test even after finding the answer. In some cases this can become a serious resource waste and hurt performance.
Now let’s see how to handle more than three cases. Suppose you write a program that asks the user to pick a fruit name from five fruits. There are six possible cases: the five correct fruit names, plus one for “wrong fruit name.” You’d use multiple elif blocks:
>>> answer = 'strawberry'
>>>
>>> if answer == 'banana':
... print('banana is correct.')
... elif answer == 'strawberry':
... print('strawberry is correct.')
... elif answer == 'apple':
... print('apple is correct.')
... elif answer == 'orange':
... print('orange is correct.')
... elif answer == 'watermelon':
... print('watermelon is correct.')
... else:
... print('{} is not correct'.format(answer))
...
strawberry is correct.You can simplify this code by storing the fruit names in a list and checking membership:
>>> fruits = ['banana', 'strawberry', 'apple', 'orange', 'watermelon']
>>>
>>> if answer in fruits:
... print('{} is correct'.format(answer))
... else:
... print('{} is not correct'.format(answer))
...
strawberry is correctWhen using if, you’ll sometimes need to test two or more conditions at once. For that, use nested if.
Problem: find a number that satisfies both of the following.
- Condition 1:
x > 0 - Condition 2:
x < 3
To find a small positive number, you need an answer that satisfies both: positive (Condition 1) and less than 3 (Condition 2). Use a nested if:
answer = int(input('Enter a number: '))
if answer > 0:
if answer < 3:
print('{} is correct'.format(answer))
else:
print('{} is not correct'.format(answer))
else:
print('{} is not correct'.format(answer))You can collapse a nested if into a single compound condition with and:
answer = int(input('Enter a number: '))
if answer > 0 and answer < 3:
print('{} is correct'.format(answer))
else:
print('{} is not correct'.format(answer))Now let’s see how to use or to combine two if statements.
Problem: find a number that satisfies at least one of the following.
- Condition 1:
x < 3 - Condition 2:
x > 6
The answer must be smaller than 3 or larger than 6. You could use a nested if like before:
answer = int(input('Enter a number: '))
if answer < 3:
print('{} is correct'.format(answer))
else:
if answer > 6:
print('{} is correct'.format(answer))
else:
print('{} is not correct'.format(answer))Another approach: define a flag variable, set it to True when either condition matches, and check the flag at the end.
answer = int(input('Enter a number: '))
flag = None
if answer < 3:
flag = True
if answer > 6:
flag = True
if flag:
print('{} is correct'.format(answer))
else:
print('{} is not correct'.format(answer))The cleaner version uses or:
answer = int(input('Enter a number: '))
if answer < 3 or answer > 6:
print('{} is correct'.format(answer))
else:
print('{} is not correct'.format(answer))💡 Today’s tip
When
ifstatements get deeply nested, readability suffers. Prefer collapsing them into a single compound condition.
if tests convert every condition to a boolean — True or False. In Python, certain objects evaluate to False when converted to boolean.
The following objects are treated as False in an if test:
FalseNone- Integer
0 - empty
string - empty
list - empty
tuple - empty
dictionary
Convert each to boolean with bool:
>>> bool(False)
False
>>> bool(None)
False
>>> bool(0)
False
>>> bool('')
False
>>> bool([])
False
>>> bool(())
False
>>> bool({})
FalseVerify that these are treated as falsy inside an if:
>>> if condition == True:
... print('true')
... else:
... print('false')
...
falseFor clarity I wrote condition == True, but you can omit it:
>>> condition = {}
>>>
>>> if condition: # True can be omitted
... print('true')
... else:
... print('false')
...
falseUsing this, “x is not 0” can be replaced with the shorter form:
x = 1
if x != 0:
print('x is not zero')
if x:
print('x is not zero')You can flip a True to False (or vice versa) with not:
x = 0
if x == 0:
print('x is zero')
if not x:
print('x is zero')A list with length greater than zero is truthy, and an empty list is falsy. So instead of comparing length, just use the list itself:
my_list = [1, 2, 3]
if len(my_list) > 0:
print('my_list has at least one item')
if my_list:
print('my_list has at least one item')if statements aren’t hard to use, but using them poorly can break the structure of your program and hurt performance. Practice the patterns above well.
In the next lesson we’ll cover the while loop.