This article is participating in Python Theme Month. See the link for details

Programming often involves checking a list of conditions and deciding what to do. In Python, the if statement lets you check the current state of your program and take action accordingly.

A simple example

  • Here is a short example of how to use an if statement to properly handle a special case. Suppose you have a list of cars and want to print out the name of each of them. For BMW, the car name needs to be all caps.
cars = ['audi'.'bmw'.'subaru'.'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
Copy the code

The test conditions

  • At the heart of every if statement is an expression with a value of True or False, called a conditional test.
  • Python decides whether to execute the code in the if statement based on whether the conditional test is True or False.

Check for equality

  • The simplest conditional test checks whether the value of a variable is equal to a particular value:
In [1]: car = 'bmw'

In [2]: car == 'bmw'
Out[2] :True
Copy the code
  • This equality operator returns True if the values on both sides are equal, False otherwise.

Ignore case when checking for equality

  • Case sensitive when checking for equality in Python.
In [1]: car = 'Audi'

In [2]: car == 'audi'
Out[2] :False
Copy the code
  • If case is important, this behavior has its advantages. If case does not matter and you just want to check the value of the variable, convert the value of the variable to lower case and compare:
In [1]: car = 'Audi'

In [2]: car == 'audi'
Out[2] :False

In [3]: car.lower() == 'audi'
Out[3] :True

In [4]: car
Out[4] :'Audi'
Copy the code
  • methodslower()It does not affect the variables associated with itcarThe value of the.

Check for discrepancies

  • Here’s another if statement to show how to use the inequality operator:
requested_topping = 'mushrooms'
ifrequested_topping ! ='anchovies':
    print("Hold the anchovies!")
Copy the code

The numerical comparison

answer = 17
ifanswer ! =42:
    print("That is not the correct answer. Please try again!")
Copy the code

Check for multiple conditions

  1. useandCheck for multiple conditions
  • For example, check whether two people are both younger than 21:
age_0 = 22
age_1 = 18

print(age_0 >= 21 and age_1 >= 21)

age_1 = 22

print(age_0 >= 21 and age_1 >= 21)
Copy the code
  1. useorCheck for multiple conditions
  • Check both people’s ages again, but only if at least one person is at least 21 years old:
age_0 = 22
age_1 = 18

print(age_0 >= 21 or age_1 >= 21)

age_1 = 18

print(age_0 >= 21 or age_1 >= 21)
Copy the code

Check whether a particular value is included in the list

  • Sometimes you must check that the list contains a particular value before performing an operation.
  • To determine if a particular value is included in the list, use a keywordin.
requested_toppings = ['mushrooms'.'onions'.'pineapple']

print('mushrooms' in requested_toppings)

print('pepperoni'in requested_toppings)

Copy the code

Checks whether a particular value is not included in the list

  • There are also times when it is important to make sure that a particular value is not included in the list. In this case, you can use keywordsnot in.
banned_users = ['andrew'.'carolina'.'david']
user = 'marie'
if user not in banned_users:
    print(f"{user.title()}, you can post a response if you wish.")
Copy the code

Boolean expression

  • It is simply an alias for conditional testing.
  • As with conditional expressions, the result of Boolean expressions is eitherTrue, or forFalse.

If statement

  • There are many types of if statements, and choosing which one to use depends on the number of conditions you are testing.

Simple if statement

  • The simplest if statement has only one test and one action:
age = 19

if age >= 18:
    print("You are old enough to vote!")
Copy the code

If – else statements

  • We often need to perform one action when a conditional test passes and another action when it fails.
age = 17

if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soo as you are 18!")
Copy the code

If elif – else structure

  • We often need to check more than two cases, for which we can use the if-elif-else structure provided by Python.
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
else:
    price = 40
print(f"Your admission cost is ${price}")
Copy the code

Use multiple elIF code blocks

  • You can use as many elif code blocks as you want.
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
else:
    price = 20
print(f"Your admission cost is ${price}")
Copy the code

Omit the else code block

  • Python does not require if-elif structures to be followed by else code blocks.
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
elif age >= 65:
    price = 20
print(f"Your admission cost is ${price}")
Copy the code

Testing multiple conditions

  • In general, if you want to execute only one code block, use if-elif-else; If you execute multiple blocks of code, use a series of separate if statements.

Use if statements to process lists

  • Use if statements and lists together

Checking for special elements

  • Making pizza, but out of green peppers:
requested_toppings = ['mushrooms'.'green peppers'.'extra cheese']

for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print(f"Adding {requested_topping}")

print("\nFinished making your pizza!")
Copy the code

Make sure the list is not empty

  • Check that the list of ingredients the customer ordered is empty before making the pizza. If the list is empty, check with the customer if they want plain pizza. If the list is not empty, make the pizza as in the previous example:
requested_toppings = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print(f"Adding {requested_topping}")
    
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")
Copy the code

Use multiple lists

available_toppings = ['mushrooms'.'olives'.'green peppers'.'pepperoni'.'pineapple'.'extra cheese']

requested_toppings = ['mushrooms'.'french fries'.'extra cheese']

for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print(f"Adding {requested_topping}.")
    else:
        print(f"Sorry, we don't have {requested_topping}")

print("\nFinished making your pizza!")
Copy the code

Format the if statement

  • In terms of formatting conditional tests, the only advice PEP 8 provides is to add a space on each side of comparison operators such as ==, >=, and <=.