Conditionals#
Learning Objectives
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.
if
statements 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.
It can look like this in pseudocode:
if some criteria is met:
then do this
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).
pages_written = 6
if pages_written > 3.0:
print(pages_written, "pages great! Continue writing")
Show code cell output
6 pages great! Continue writing
pages_written = 1
if pages_written > 3.0:
print(pages_written, "pages great! Continue writing")
The first if statement here where we define 6 pages written the if condition is met and the output is a printed statement as we have defined it.
In the second however, there is no output as the condition of having written more than 3 pages is not met.
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, like in this example of a list containing floats referring to how many pages have been written so far in an paper.
pages_written = [3.54, 2.07, 9.22, 1.86, 1.71]
for pages in pages_written:
if pages > 3.0:
print(pages, 'pages wauw! You have written more than 3.0 pages!')
Show code cell output
3.54 pages wauw! You have written more than 3.0 pages!
9.22 pages wauw! You have written more than 3.0 pages!
Use else
to execute a block of code when an if condition is not true#
else
can be used following an if
statement.
It allows us to specify an alternative to execute when the if
branch isn’t taken.
pages_written = [3.54, 2.07, 9.22, 1.86, 1.71]
for pages in pages_written:
if pages > 3.0:
print(pages, 'pages wauw! You have written more than 3.0 pages!')
else:
print(pages, 'pages, you need to write a bit more')
Show code cell output
3.54 pages wauw! You have written more than 3.0 pages!
2.07 pages, you need to write a bit more
9.22 pages wauw! You have written more than 3.0 pages!
1.86 pages, you need to write a bit more
1.71 pages, you need to write a bit more
elif
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.
pages_written = [3.54, 2.07, 9.22, 1.86, 1.71]
for pages in pages_written:
if pages > 9.0:
print(pages, 'that is SO many pages!')
elif pages > 3.0:
print(pages, 'that is quite a lot of pages')
else:
print(pages, 'you need a bit more pages')
Show code cell output
3.54 that is quite a lot of pages
2.07 you need a bit more pages
9.22 that is SO many pages!
1.86 you need a bit more pages
1.71 you need a bit more pages
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 focusing on the amercian grade system:
points = 85
if points >= 70:
print('grade is C')
elif points >= 80:
print('grade is B')
elif points >= 90:
print('grade is A')
Show code cell output
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 the if condition. Thus, the elif
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')
Show code cell output
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. Have a look at this scipt of the speed of a car:
speed = 10.0
if speed > 20.0:
print('moving too fast')
else:
print('adjusting speed')
speed = 50.0
Show code cell output
adjusting speed
It stays at adjusting speed as the new assignment of the value 50.0
does not automatically start the script over.
Often conditionals are used in a loop to “evolve” the values of variables. This can be done like this:
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)
Show code cell output
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#
Often, you want some combination of things to be true. You can combine relations within a conditional using an and/or or. This is called compound statements.
See also
You can read more about compound statements in the official documentation.
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
Show code cell output
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 becomes False
, 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 turns False
. 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#
Exercise 1: What does this program print?#
Suppose we have a coffee machine that adjusts brewing pressure for making really delicious espresso. The brewing pressure is currently 8.5 bars. What kind of coffee if the machine brewing at the moment?
pressure = 8.5 # Brewing pressure in bars
if pressure > 7.0:
print("Brewing delicious strong coffee")
elif pressure > 5.0:
print("Brewing regular coffee")
else:
print("Adjusting pressure for delicate espresso")
Show code cell output
Brewing delicious strong coffee
Exercise 2: Fill in the blanks#
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.
Input
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)
Output
[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)
Exercise 3: Using the input()
function#
Try out the code below. You will need to copy paste it into your own notebook.
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.
Exercise 4: The number guessing game#
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
, and else
statements to provide appropriate hints based on the user’s guess.
Hint
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)
You will need your output to look something like this:
Output
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
This problem can be solved in more than one way - however this is how we would recommend it done to provide clarity and to use the skills you have learned so far.
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.