if Statements In Python
What we want to do? We have a list of
cars
that contains the name of cars in lowercase letter. We want to print the names of all in title case expect from ‘byd’, which should be all in upper case To achieve this we will combine a for
loop with if-else
statementscars = ['toyota','honda','byd','buick']
for car in cars:
if car == 'byd':
print(car.upper())
else:
print(car.title())
Toyota
Honda
BYD
Buick
How it works? The loop in this example first checks
if
the current value of car
is ‘byd’ .If it is, the value is printed in uppercase. else
(If the value of car
is anything other than ‘byd’) it’s printed in title case.At the heart of every
if
statement is an expression that can be evaluated as True or False and is called a conditional test- If a conditional test evaluates to True, Python executes the code following the
if
statement. - If the conditional test evaluates to False, Python ignores the code following the
if
statement. If we have providedelse
statement, then that code will be executed
Single equal sign
=
is used to assign a value to a variable, whereas double equal sign ==
is to check
for equality — this equality operator returns True if the values on the left and right side of the operator match, and False if they don’t match.car = 'BYD'
car == 'byd'
False
Testing for equality is case sensitive in Python as we seen above
car = 'BYD'
car.lower() == 'byd'
True
This test would return True no matter how the value ‘BYD’ is formatted because the test is now case insensitive.
When you want to determine whether two values are not equal, we use the conditional operator
!=
— the exclamation point represents notusername = 'thor'
if username != 'spiderman':
print('Sorry, Only Spiders are welcomed!')
Sorry, Only Spiders are welcomed!
We can compare the numerals the same way as we did the strings.
your_answer = 95
correct_answer = 100
if your_answer == correct_answer:
print("You've passed the test.")
else:
print("Your answer is wrong.")
Your answer is wrong.
We can use following comparison operators :
Operator | Meaning |
---|---|
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
We can use
and
or or
to check to check the True or False status of multiple conditions:and
— when you might need two conditions to be True to take an actionor
— when you might need either of two conditions to be True to take an action
To check whether two conditions are True simultaneously, we use the keyword
and
to combine the two conditional tests.- If both conditional tests pass, the overall expression evaluates to True
- If either or both conditions fail, the expression evaluates to False.
age_1 = 15
age_2 = 21
if age_1 >= 18 and age_2 >= 18:
print("You are elible to register as team.")
else:
print("Sorry, you are not eligible to register.")
Sorry, you are not eligible to register.
To improve readability of our code, we can use parentheses
( )
around the individual tests, but they are not requiredif (age_1 >= 18) and (age_2 >= 18):
The
or
condition returns True when either or both of the individual tests pass. It will return False only when both individual tests fail.age_1 = 15
age_2 = 21
if age_1 >= 18 or age_2 >= 18 :
print("You are elible to register as team.")
else:
print("Sorry, you are not eligible to register.")
You are elible to register as team.
Sometimes, it’s important to check whether a list contains a certain value before taking an action. To find out whether a particular value is already in a list, we use the keyword
in
.guests = ['ironman','spiderman','superman']
on_door = 'antman'
if on_door in guests:
print(f"Welcome to the Club, {on_door.title()}")
else:
print(f"Sorry {on_door.title()}, you are not in the guests list")
Sorry Antman, you are not in the guests list
Other times, we would like to know if a value does not appear in a list. In this case, we can use the keyword
not in
this situation.banned_codes = ['code5','code10','code15']
user_code = 'code10'
if user_code not in banned_codes:
print("Your code is valid")
else:
print("Your code is invalid")
Your code is invalid
A Boolean expression is just another name for a conditional test whose value is either True or False. We have studied earlier in part 1 about Boolean data type and the same logic applies here.
has_arrived = True
if has_arrived:
print("Welcome to the club")
Welcome to the club
There are few types of
if
statements, and your choice of which to use depends on the number of conditions you need to test.Some basic examples of
if
statements have been discussed, the general syntax of if
statement is as follows:if conditional_test:
things to do something
Logic → If the conditional test evaluates True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement
user_age = 31
required_age = 21
if user_age >= required_age:
print("You are elible to enter the arena")
You are elible to enter the arena
NOTE: All indented lines after an
if
statement will be executed if the test passes, and ignored if the test failsAn
if- else
block is similar to a simple if
statement, but the else
statement allows you to execute some code when the conditional test under if
failsuser_age = 17
required_age = 21
if user_age >= required_age:
print("You are elible to enter the club")
else:
print("You are not eligible to enter the club")
You are not eligible to enter the club
Often, you’ll need to test more than two possible situations, for these situations you can use Python’sif- elif- else
syntax.
Remember that Python executes only one block in an
if- elif- else chain
depending on which condition is True. That is, it runs each conditional test in order until one passes, when a test passes, the code following that test is executed and Python skips the rest of the tests For example, the price for museum varies with age:- For kids under 4 age, price is $0
- For kids and teen above 4 years and less than 18 years, ticket price is $5
- For anyone above 18 years, price is $10
entrant_age =12
if entrant_age < 4:
price = 0
elif entrant_age < 18:
price = 5
else:
price = 10
print(f"Your price is ${str(price)}")
Your price is $5
You can see how the logic of
if-elif-else
works :- for
elif
code block, we don’t need to mention that price is $5 for age greater than 4 years but less than or equal to 18 years. Because, if theif
condition passes, the elif and else code block will be ignored else
block serves as fallback, if none of above conditions are True
To check multiple cognitions , you can use as manyelif
blocks in your code as you like
For example, for the above example, we can create another age group — price is $2 for anyone with age greater than 60 years
entrant_age =65
if entrant_age < 4:
price = 0
elif entrant_age < 18:
price = 5
elif entrant_age < 60:
price = 10
else:
price = 2
print(f"Your price is ${str(price)}")
Your price is $2
Python does not require anelse
block at the end of anif- elif
chain.
Sometimes an else block is useful; sometimes it is more meaningful to use an additional elif statement that catches the specific condition of interest, in this way you exhaust all the available options that your program should run on:
entrant_age =65
if entrant_age < 4:
price = 0
elif entrant_age < 18:
price = 5
elif entrant_age < 60:
price = 10
elif entrant_age >=60:
price = 2
print(f"Your price is ${str(price)}")
Your price is $2
💡The
else
block is a catchall statement. It means, it will only be executed if all earlier conditions are False , which can lead to invalid results in our code. Therefore, to avoid this situation, if you have a specific final condition you are testing for, consider using a final elif
block and omit the else
block.Until now, we only executed one set of code and ignore all others. However, we can use more than one
if
statements to run more than one block of code. This leads us to define some rules:- If you want only one block of code to run, use an
if- elif-else chain
- If more than one block of code needs to run, use a series of independent
if
statements
vips = ['superman','spiderman']
if 'superman' in vips:
print ("Welcome, Superman")
if 'spiderman' in vips:
print("Welcome, Spiderman")
if 'antman' in vips:
print ("Welcome, Antman")
print("\nWelcome to all VIPs to join our event")
Welcome, Superman
Welcome, Spiderman
Welcome to all VIPs to join our event
PEP 8 recommends to use a single space around comparison operators:
if code > 8
is better than
if code>8
Let’s first make a list of few items and store it inside the variable
cart_items
Then we can use the for
loop to print the items inside cart_items
cart_items = ['bananas','apples','oranges']
for item in cart_items:
print (f"Shipping {item.title()}")
print("\nAll requested items are shipped")
Shipping Bananas
Shipping Apples
Shipping Oranges
All requested items are shipped
Now we will use the
if-else
statement with in a for
loopcart_items = ['bananas','apples','oranges']
for item in cart_items:
if item == 'apples':
print("Sorry, apples are out of stock")
else:
print(f"Shipping {item.title()}")
print("\nShipped all items")
Shipping Bananas
Sorry, apples are out of stock
Shipping Oranges
Shipped all items
It’s useful to check whether a list is empty before running a
for
loop. This will avoid getting any errors for performing operation on empty listcart_items = []
if cart_items:
for item in cart_items:
print ("Shipping {item.title()}")
print("\nAll items are shipped")
else:
print("Your basket is empty")
Your basket is empty
We can combine the above two examples in the following way:
cart_items = ['bananas','apples','oranges']
if cart_items:
for item in cart_items:
if item == 'apples':
print("Sorry, apples are out of stock")
else:
print(f"Shipping {item.title()}")
print("\nShipped all items")
else:
print("Your basket is empty")
Shipping Bananas
Sorry, apples are out of stock
Shipping Oranges
Shipped all items
We can use two list to check whether content of one list is available
in
second list:cart_items = ['bananas','apples','oranges']
available_items = ['bananas','oranges','pears']
for item in cart_items:
if item in available_items:
print(f"Shipping {item.title()}")
else:
print(f"Sorry, {item} is out of stock")
print("\nShipped all items")
Shipping Bananas
Sorry, apples is out of stock
Shipping Oranges
Shipped all items
Last modified 4mo ago