Conditional execution is often required in an application as some actions need to be performed only when a certain condition is met. Example, when dividing two numbers, you need to check the value of numbers and perform division only when the divisor is greater than zero. Or when creating a menu based application, different actions need to be performed as per the menu option selected by the user. Python provides following constructs to control execution flow based on conditions.
if statement
This statement is followed by a conditional expression and a set of statements that form part of it. The conditional statement ends with a colon(:) and should return either True
or False
. If it returns True
, then the statements that are part of it(also called if-block) are executed else they are by-passed as it they do not exist. An example of if-statement follows
x = 5 if x == 5: print("Condition is true")
Above code contains an if statement with a conditional statement that compares the value of a variable with 5. Notice the comparison operator(==) and a colon(:) at the end. Notice that the print statement is one tab or a group of spaces away. This is python way of grouping statements together. It is not necessary to give multiple spaces, a single space will also be sufficient.
It is also possible to combine multiple statements as a part of if-block. Let’s understand how.
As explained above, python follows indentations to identify statements that belong to a block. This means all statements at same indentation level are treated as belonging to same block. Thus, to make multiple statements as part of if block, place all of them at the same indentation level as show below.
x = 5 if x == 5: print("Condition is true") # part of if-block x = x + 10 # part of if-block print("x is increased by 10") # part of if-block print("Not part of if block") # this is outside if-block
Above code has if-block which contains 3 statements and will be executed only if the condition is True. Last statement is not part of if block and is executed irrespective of the result of condition.
Using Multiple conditions in if
Till now we saw only one condition in if. But it is also possible to use multiple conditions in if statement. Conditions are either separated by and
operator or an or
operator. When conditions are separated by and
, this means that when all conditions will be True, then if-block will be executed.
When conditions are separated by or, then any one condition should be True
for if-block to be executed.
x = 5 y = 10 if x == 5 or y == 20: # two conditions separated by and print("x is 5") # will be executed since first condition is True if x == 5 and y == 20: # two conditions separated by or print("x = 5, y = 20 ") # will not execute since both conditions are False
if-elif statment
There are times when you need to test multiple related conditions but execute only one of them. Example, calculate ticket charges based on the age of a person. Ticket prices are different for children between 1-5 years, 6-17 years, young persons between age groups 18-30 etc. One way to put multiple if-blocks checking each age group. But, the problem with this approach is that all if conditions will be evaluated which is not correct. Another way is to use if-elif construct which is specially designed for this purpose.
Syntax:
if condition: statement 1 statement 2 # more statements elif condition: statement 1 statement 2
Syntax is same as if
construct in that every if
is followed by a condition and a set of statements. Statements will be executed only when the condition of if
statement evaluates to True
. Also, all statements at same indentation level after if
are treated of same block.
Next condition is given using elif
statement whose syntax is same as that of if
statement.
Example,
age = 5 if 1 <= age <= 5: print('Age between 1 and 5') elif 6 <= age <= 17: print('Age between 6 and 17') elif 18 <= age <= 30: print('Age between 18 and 30')
Above code checks different age groups and executes print statement of the block whose condition returns True.
Remember that only one block will be executed. That is the main benefit of if-elif
statement.
else statement
When there is always one condition which should be executed when all the other conditions are False, else block is used. This block can be used with a single if
block or if-elif
blocks. When used with any of these, else block should always be placed at last since it will be executed only when all other conditions evaluate to False. Example,
age = 0 if 1 <= age <= 5: print('Age between 1 and 5') elif 6 <= age <= 17: print('Age between 6 and 17') elif 18 <= age <= 30: print('Age between 18 and 30') elif 30 < age: print('Age more than 30') else: print('Age not valid!')