search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Python | if else statement

schedule Aug 10, 2023
Last updated
local_offer
Python
Tags
tocTable of Contents
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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 true
else:
   # 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 = 19
if age >= 20:
   print("Old enough")

else:
   print("Too young")
Too young

The equivalent to above using concise syntax:

age = 19
print("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 = 9
if 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 = 15
if 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.

NOTE

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 = -15
if 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 = -15
if 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
robocat
Published by Arthur Yanagisawa
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!