Python | if else statement
Start your free 7-days trial now!
Similar to the if
statement, the if else
statement in Python allows us to perform certain actions if a particular expression evalutes to true. However, unlike the if
statement, the if else statement allows us to perform a separate action in the case the test expression evaluates to false.
Syntax
if test expr: # code to execute if test expr evaluates to trueelse: # code to execute if test expr evalutes to false
More concise syntax:
(code to execute if true) if test expr else (code to execute if false)
Example
If-else
To tell a person whether they are old enough or not to buy alcohol:
age = 19if age >= 20: print("Old enough")
else: print("Too young")
Too young
The equivalent to above using concise syntax:
age = 19print("Old enough") if age >=20 else print("Too young")
Too young
If-elif-else
We can also specify multiple scenarios using if-elif-else
statements:
age = 9if age >= 20: print("We can confirm you are old enough to buy alcohol.")
elif 10 <= age < 20: print("Sorry you are too young to buy alcohol. Come back when you are 20.")
else: print("Where are your parents? You shouldn't be wondering around alone!")
Where are your parents? You shouldn't be wondering around alone!
Running the above code with age=15
:
age = 15if age >= 20: print("We can confirm you are old enough to buy alcohol.")
elif 10 <= age < 20: print("Sorry you are too young to buy alcohol. Come back when you are 20.")
else: print("Where are your parents? You shouldn't be wondering around alone!")
Sorry you are too young to buy alcohol. Come back when you are 20.
In this way we can specify as many conditions as we want using multiple elif
blocks.
The else
block is a catch all statement. It will execute when none of the conditions above it has been met. This means in some cases, even if the input data is invalid, the else
block will execute. Therefore, it is possible to omit the else
block and use elif
blocks to make sure the input data matches a particular condition before executing.
For example, in our current program a negative age will still result in the else
block executing:
age = -15if age >= 20: print("We can confirm you are old enough to buy alcohol.")
elif 10 <= age < 20: print("Sorry you are too young to buy alcohol. Come back when you are 20.")
else: print("Where are your parents? You shouldn't be wondering around alone!")
Where are your parents? You shouldn't be wondering around alone!
Obviously a negative age does not make sense so we can remove the else
block and replace with elif
:
age = -15if age >= 20: print("We can confirm you are old enough to buy alcohol.")
elif 10 <= age < 20: print("Sorry you are too young to buy alcohol. Come back when you are 20.")
elif 0 <= age < 10: print("Where are your parents? You shouldn't be wondering around alone!")
elif age < 0: print("We think you input your age wrong, please try again")
We think you input your age wrong, please try again