The if Statement in Python

The Python if statement selects actions to perform and it’s the primary selection tool in Python. It represents a large part of the logic a Python program possesses. The if statement may contain other statements, including other if statements. You can combine statements sequentially (they execute one after another), and in a nested fashion (they execute only under certain conditions).

Syntax

if test1:
	statements1
elif test2:
	statements2
else:
	statements3

Examples

>>> a = 2
>>> b = 3
>>> if a + b == 5:
...     print('correct')
... else:
...     print('wrong')
... 
correct

Multiway Branching

>>> a = 'wolf'
>>> if a == 'rabbit':
...     print('Calm down')
... elif a == 'big dog':
...     print('Might be dangerous')
... else:
...     print('Run!')
... 
Run!

Dictionary-based ‘switch’

>>> mybike = 'honda'
>>> print({'honda': 2800,
...        'yamaha': 2600,
...        'suzuki': 2400}[mybike])
2800
>>>
>>> # The equivalent if statement
>>> if mybike == 'suzuki':
...     print(2400)
... elif mybike == 'yamaha':
...     print(2600)
... elif mybike == 'honda':
...     print(2800)
... else:
...     print('No bike selected!')
... 
2800

Handling switch defaults

>>> bikes = {'honda': 2800,
...          'yamaha': 2600,
...          'suzuki': 2400}
>>> print(bikes.get('honda', 'the best'))
2800
>>> print(bikes.get('yamaha', 'good'))
2600

An in membership test in an if statement can have the same effect:

>>> mychoice = 'kawasaki'
>>> if mychoice in bikes:
...     print(bikes[mychoice])
... else:
...     print('There is no such bike!')
... 
There is no such bike!

And the try statement is a general way to handle defaults by catching and handling the exceptions they’d otherwise trigger:

>>> try:
...     print(bikes[mychoice])
... except KeyError:
...     print('Choose something from the shop!')
... 
Choose something from the shop!

Leave a Reply