Categories
Python

Part 4: if STATEMENTS

In this article, we will learn various types of conditional tests, how to use these conditional tests with if statements, various types of if statements, and, to use if statement with Python’s for loop

A SIMPLE EXAMPLE

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 statements

cars = ['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.

1. CONDITIONAL TESTS

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 provided else statement, then that code will be executed

1.1. Checking for Equality

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

Ignoring Case When Checking for Equality

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.

1.2. Checking for Inequality

When you want to determine whether two values are not equal, we use the conditional operator != — the exclamation point represents not

username = 'thor'
if username != 'spiderman':
    print('Sorry, Only Spiders are welcomed!')
Sorry, Only Spiders are welcomed!

1.3. Numerical Comparisons

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.

Using various mathematical operators

We can use following comparison operators :

OperatorMeaning
>greater than
<less than
>=greater than or equal to
<=less than or equal to

1.4. Checking Multiple Conditions

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 action
  • or — when you might need either of two conditions to be True to take an action

Using and condition

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 required

if (age_1 >= 18) and (age_2 >= 18):

Using or condition

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.

1.5. Checking Whether a Value is in a List

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

1.6. Checking Whether a Value is not in a 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

1.7. Boolean Expressions

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

2. Types of if STATEMENTS

There are few types of if statements, and your choice of which to use depends on the number of conditions you need to test.

2.1 Simple if Statements

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 fails

2.2. if-else Statements

An 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 fails

user_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

2.3. The if-elif-else Chain

Often, you’ll need to test more than two possible situations, for these situations you can use Python’s if- 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 the if condition passes, the elif and else code block will be ignored
  • else block serves as fallback, if none of above conditions are True

2.4. Using Multiple elif Blocks

To check multiple cognitions , you can use as many elif 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

2.5. Omitting the else Block

Python does not require an else block at the end of an if- 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.

2.6. Testing Multiple Conditions

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

2.7 STYLING YOUR if STATEMENTS

PEP 8 recommends to use a single space around comparison operators:

if code > 8

is better than

if code>8

3. USING if STATEMENTS WITH LISTS

3.1 Checking: an item inside list

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

if statement inside the for loop

Now we will use the if-else statement with in a for loop

cart_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

3.2. Checking: List Is Not Empty

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 list

cart_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

Combining two if-else statements block

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

3.3. Using Multiple Lists

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

Leave a Reply