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")
Hide 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!')
Hide 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 ifstatement. 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')
Hide 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 - like else - is only executed if the if 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')
Hide 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')
Hide 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')
Hide 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
Hide code cell output
adjusting speed

It stays at adjusting speed as the new assignment of the value 50.0does 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)
Hide 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.

Example: Analysing social media impact#

Imagine you are working on a project to analyse social media posts for a campaign. Your goal is to categorise posts based on their engagement metrics, such as the number of likes and shares, to determine their impact.
You have data that includes the engagement metrics of various posts, and you want to classify them to understand their effectiveness better.

# Lists of engagement metrics: likes and shares for each social media post
likes = [300, 150, 800, 100, 50]
shares = [50, 30, 120, 10, 20]

# Loop through each post's data
for i in range(5):
    if likes[i] > 500 and shares[i] > 50:
        print("High impact post. Excellent engagement!")
        
    elif likes[i] > 100 and likes[i] <= 500 and shares[i] <= 50:
        print("Moderate impact post. Decent engagement.")
        
    elif likes[i] <= 100 and shares[i] <= 50:
        print("Low impact post. Needs improvement.")
        
    else:
        print("Unexpected data. Check the engagement metrics.")
Hide code cell output
Moderate impact post. Decent engagement.
Moderate impact post. Decent engagement.
High impact post. Excellent engagement!
Low impact post. Needs improvement.
Low impact post. Needs improvement.

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 likes[i] <= 100 or shares[i] >= 500 and likes[i] > 50:

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 (likes[i] < 100 or likes[i] > 500) and shares[i] > 50:

Or:

if likes[i] < 100 or (likes[i] > 500 and shares[i] > 50):

Notice

Notice that the two statements above test for something different!
The first statement requires:
likes to be outside the range of 100 to 500 and the shares to be greater than 50.
The second statement requires either of these two to be true:
likes must be smaller than 100,
or:
likes must be greater than 500 and shares must be greater than 50.


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
Hide 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")
Hide 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]

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: ")

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:

  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.

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.

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.