Conditionals
Overview
Teaching: 25 min
Exercises: 20 minQuestions
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
- An
if
statement (more properly called a conditional statement) controls whether some block of code is executed or not. - The structure is similar to a
for
statement:- First line opens with
if
and ends with a colon. - Body containing one or more statements is indented (usually by 4 spaces or tab).
- First line opens with
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
- There is not much point in using a conditional when we know the value (as above).
- But it is useful when we have a collection to process.
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
else
can be used following anif
.- It allows us to specify an alternative to execute when the
if
branch isn’t taken.
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
- You may want to provide several alternative choices, each with its own test.
- Use
elif
(short for “else if”) and a condition to specify these. - Must always be associated with an
if
. - Must come before the
else
(which is the “catch all”). elif
- likeelse
- is only executed if theif
condition is not.
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
- Python steps through the branches of the conditional in order, testing each in turn.
- But if one conditional is fulfilled, Python will “step out of” the statement and not test the following conditionals.
- So ordering matters!
- Take a look at this script:
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
- What is the problem with the script above?
- The problem is that a grade can never be higher than ‘C’, since any
points
above 70 will be “caught” by theif
condition. Thus, theelif
conditions will never be tested. - A better way to write the above script, would be:
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
- Remember that Python scripts are run “chronologically”, i.e., from the top down.
- This means, that a script will not automatically go back and re-evaluate if values change.
speed = 10.0
if speed > 20.0:
print('moving too fast')
else:
print('adjusting speed')
speed = 50.0
adjusting speed
- Often conditionals are used in a loop to “evolve” the values of variables.
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/oror
.- 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
andor
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 thespeed
to be greater than 20.- The second statement requires either of these two to be true:
mass
must be smaller than 2, ormass
must be greater than 5 andspeed
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
- The loop will continue to execute as long as the condition remains
True
. - Once the condition becomes
False
, the loop will exit.
count = 1
while count <= 5:
print(count)
count += 1
1
2
3
4
5
- In this example, the loop prints numbers from 1 to 5.
- The
count
variable is incremented in each iteration until it becomes greater than 5, at which point the condition becomesFalse
, and the loop stops.
Infinite loops
- Remember always to set a counter or similiar to make sure the
while
loop stops at some point. Otherwise, you create an infinite loop!- If you accidentally create an infinite loop, you can stop it by pressing the “stop” button (“Interrupt the kernel”) at the top of Jupyter Lab (and similar).
- If you don’t have a stop button, use CTRL-C to stop the script.
- Take a look at the code below. What is wrong with it?
i = 0
while True:
print(i)
i += 1
- The problem is that the
while
condition never turnsFalse
. Thus, the loop will carry on infinitely. - A way to stop the loop could be:
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:
- Generate a random secret number between 1 and 20.
- Ask the user to guess the secret number.
- 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.”
- Allow the user to keep guessing until they correctly guess the number.
- 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
, andelse
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 anif
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.