Like humans, computers must be able to repeat a set of actions. They must also be able to select an action to perform in a particular situation. This unit will therefore largely focus on conditional tests.

Simply put, a conditional statement, or if statement, lets us make decisions in Python.


Simple If Statements:

  • The simplest kind of if statement has one test and one action:
1if conditionalTest:
2	do something
  • If the conditional test evaluates to True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement.

If-else statements:

  • An if-else block is similar to a simple if statement, but the else statement allows you to define an action or set of actions that are executed when the conditional test fails.
  • Example: We can display a message if a person is old enough to drink and then add a message for anyone who is not old enough to drink:
python
1age = 19
2if age >= 21:
3    print("You are old enough to drink!")
4else:
5    print("Sorry, you are too young to drink.")
  • Output: Because the conditional test failed, the code in the else block was executed.
1Sorry, you are too young to drink.

What does a Conditional Test Inside a for Loop Look Like?

  • At the heart of every if statement is an expression that can be evaluated as true or false and is called a conditional test.
  • The following example shows how if tests let you respond to special situations correctly.
    • Example: Imagine if you have a list of cars and you want to print out the name of each car.
      • Car names are proper names, so the names of most cars should be printed in title case.
python
1cars = ["honda", "subaru", "bmw", "toyota"]
2for car in cars:
3    if car == "bmw":
4        print(car.upper())
5    else:
6        print(car.title())
  • The loop in this example first checks if the current value of car is “bmw” in line 4. If it is, the value is printed in upper case. If the value of car is anything other than “BMW”, it is printed in title case:
1Honda
2Subaru
3BMW
4Toyota