This lesson is in the early stages of development (Alpha version)

Conditionals

Overview

Teaching: 25 min
Exercises: 20 min
Questions
  • How can you use conditional statements to control program flow?

Objectives
  • Explain the use of if and else statements and simple Boolean expressions.

  • Explain the use of while statements.

  • Trace the execution of unnested conditionals and conditionals inside loops.

Use if statements to control whether or not a block of code is executed

mass = 3.54
if mass > 3.0:
    print(mass, 'is larger than 3.0')

mass = 2.07
if mass > 3.0:
    print (mass, 'is larger than 3.0')
3.54 is larger than 3.0

Conditionals are often used inside loops

masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
    if m > 3.0:
        print(m, 'is larger than 3.0')
3.54 is larger than 3.0
9.22 is larger than 3.0

Use else to execute a block of code when an if condition is not true

masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for mass in masses:
    if mass > 3.0:
        print(mass, 'is larger than 3.0')
    else:
        print(mass, 'is smaller than 3.0')
3.54 is larger than 3.0
2.07 is smaller than 3.0
9.22 is larger than 3.0
1.86 is smaller than 3.0
1.71 is smaller than 3.0

Use elif to specify additional tests

masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for mass in masses:
    if mass > 9.0:
        print(mass, 'is HUGE')
    elif mass > 3.0:
        print(mass, 'is larger')
    else:
        print(mass, 'is smaller')
3.54 is larger
2.07 is smaller
9.22 is HUGE
1.86 is smaller
1.71 is smaller

Conditions are tested once, in order

points = 85
if points >= 70:
    print('grade is C')
elif points >= 80:
    print('grade is B')
elif points >= 90:
    print('grade is A')
grade is C
points = 85
if points >= 90:
    print('grade is A')
elif points >= 80:
    print('grade is B')
elif points >= 70:
    print('grade is C')
grade is B


speed = 10.0
if speed > 20.0:
    print('moving too fast')
else:
    print('adjusting speed')
    speed = 50.0
adjusting speed
speed = 10.0
for i in range(5): # execute the loop 5 times
    print(i, ':', speed)
    if speed > 20.0:
        print('moving too fast')
        speed = speed - 5.0
    else:
        print('moving too slow')
        speed = speed + 10.0
print('final speed:', speed)
0 : 10.0
moving too slow
1 : 20.0
moving too slow
2 : 30.0
moving too fast
3 : 25.0
moving too fast
4 : 20.0
moving too slow
final speed: 30.0


Compound statements; using and, or, and parentheses

  • Often, you want some combination of things to be true.
  • You can combine relations within a conditional using and and/or or.
  • This is called compound statements.
  • Continuing the example above, suppose you have:
mass     = [ 3.54,  2.07,  9.22,  1.86,  1.71]
speed    = [10.00, 20.00, 30.00, 25.00, 20.00]

for i in range(5):
    if mass[i] > 5 and speed[i] > 20:
        print("Fast heavy object. Duck!")
    elif mass[i] > 2 and mass[i] <= 5 and speed[i] <= 20:
        print("Normal traffic")
    elif mass[i] <= 2 and speed[i] <= 20:
        print("Slow light object. Ignore it.")
    else:
        print("Whoa! Something is up with the data. Check it.")
  • Just like with arithmetic, you can and should use parentheses whenever there is possible ambiguity.
  • If no parentheses are used, Python will read code based on operator precedence.
  • However, a good general rule is to always use parentheses when mixing and and or in the same condition.
  • That is, instead of:
if mass[i] <= 2 or mass[i] >= 5 and speed[i] > 20:

You should write it like one of these two so it is perfectly clear to a reader (and to Python) what you really mean:

if (mass[i] < 2 or mass[i] > 5) and speed[i] > 20:
if mass[i] < 2 or (mass[i] > 5 and speed[i] > 20):
  • Notice that the two statements above test for something different!
  • The first statement requires mass to be outside the range of 2 to 5 and the speed to be greater than 20.
  • The second statement requires either of these two to be true:
    1. mass must be smaller than 2, or
    2. mass must be greater than 5 and speed must be greater than 20.

While loops

In Python, a while loop allows you to repeatedly execute a block of code as long as a certain condition is true. This can be useful when you want to perform an action multiple times until a specific condition is met.

The while syntax

The basic structure of a while loop in Python is as follows:

while condition:
    # Code to be executed as long as the condition is true
count = 1
while count <= 5:
    print(count)
    count += 1
1
2
3
4
5

Infinite loops

i = 0
while True:
    print(i)
    i += 1
i = 0
while i <= 100:
    print(i)
    i += 1

Exercises:

Tracing Execution

What does this program print?

pressure = 71.9
if pressure > 50.0:
    pressure = 25.0
elif pressure <= 50.0:
    pressure = 0.0
print(pressure)

Solution

25.0

Trimming Values

Fill in the blanks so that this program creates a new list containing zeroes (0) where the original list’s values were negative and ones (1) where the original list’s values were zero or positive.

original = [-1.5, 0.2, 0.4, 0.0, -1.3, 0.4]
result = ____
for value in original:
    if ____:
        result.append(0)
    else:
        ____
print(result)
[0, 1, 1, 1, 0, 1]

Solution

original = [-1.5, 0.2, 0.4, 0.0, -1.3, 0.4]
result = []
for value in original:
   if value < 0:
       result.append(0)
   else:
      result.append(1)
print(result)

Using the input() function

  • Try out the code below.
  • What does the script do?
  • What does the function input() do?
user_input = ""
while user_input != "quit":
  user_input = input("Enter 'quit' to exit: ")

Solution

  • This loop continuously asks the user for input until they type “quit.”
  • It checks the value of user_input in each iteration.

A note on the input() function

  • Note, the return value of the input() function is always a string, even if the input value looks like another data type.
  • I.e., if the user inputs 3, the output will be the string '3'.
  • To convert the return value to an integer, you can use the int() function.

The Number Guessing Game with hints

In this final exercise, we will write a Python program for a number guessing game!

This exercise builds on the knowledge you have gathered in this course up till now.
Try to solve it without looking at the solution.

Take it easy, don’t sweat it, and have fun writing your first real Python script!

The program should do the following:

  1. Generate a random secret number between 1 and 20.
  2. Ask the user to guess the secret number.
  3. Provide hints to the user based on their guess:
    • If the guess is correct, print “Congratulations! You guessed the correct number.”
    • If the guess is too low, print “Too low. Try again.”
    • If the guess is too high, print “Too high. Try again.”
  4. Allow the user to keep guessing until they correctly guess the number.
  5. Count and display the number of attempts it took for the user to guess correctly.

Requirements:

  • Use a while loop to repeatedly ask the user for their guess until they guess correctly.
  • Use if, elif, and else statements to provide appropriate hints based on the user’s guess.

Hints:

  • You will need to use the input() function introduced in the exercise above.
  • We expect the users to only type in integers.
  • You can use the random module to generate the secret number. Here’s an example of how to import and use it:
import random

# Generate a random secret number between 1 and 20
secret_number = random.randint(1, 20)

Sample Output (simplified):

You will need your output to look something like this:

Welcome to the Number Guessing Game!

Guess the secret number (1-20): 10
Too low. Try again.

Guess the secret number (1-20): 15
Too high. Try again.

Guess the secret number (1-20): 12
Congratulations! You guessed the correct number in 3 attempts.

Solution

Are you really sure, you want to see the solution yet?
Only look if you have solved it yourself.
Remember:

Python pain is temporary, pride is forever!

“Yes, I am weak and I want to see the solution!”

import random

# Generate a random secret number between 1 and 20
secret_number = random.randint(1, 20)

# Initialize variables
attempts = 0
guessed_correctly = False

print("Welcome to the Number Guessing Game!")

while not guessed_correctly:
    # Ask the user to guess the secret number
    user_guess = int(input("Guess the secret number (1-20): "))
    
    # Increment the attempts counter
    attempts = attempts + 1

    # Check if the guess is correct, too low, or too high
    if user_guess == secret_number:
        guessed_correctly = True
        print("Congratulations! You guessed the correct number in", attempts, "attempts.")
    elif user_guess < secret_number:
        print("Too low. Try again.")
    else:
        print("Too high. Try again.")

Key Points

  • Use if statements to control whether or not a block of code is executed.

  • Conditionals are often used inside loops.

  • Use else to execute a block of code when an if condition is not true.

  • Use elif to specify additional tests.

  • Conditions are tested once, in order.

  • A while loop allows you to repeatedly execute a block of code as long as a certain condition is true.