Preparation#

Reading material#

This week corresponds to parts of Think Python (TP) Chapter 5 Conditionals and Recursion. The sections covered are: if statement, The else clause, Chained conditionals, and Nested conditionals.

Alternatively, conditionals are also covered in the lecture notes for the CS50 Course, Lecture 1 Conditionals, only the first 4 sections.

Note about the reading material and preparation exercises. The reading material explains concepts, while the preparation exercises let you try them out. You can start with either. Some read first, others begin with exercises and use the book as needed. If programming is challenging, read first, do the exercises, then review the book.

Copy-and-Run#

Explanation of the Copy-and-Run exercises. As explained last week, in Copy-and-Run (CaR) exercises, you’ll be provided with code that you should copy into your Python environment and run. You will then observe the outcome, usually a printed result. You should try to understand why the code produces the output that it does. It is also a good idea to try to predict what the output will be before running the code.

Motivation. You’ve learned that code is executed line by line, with every line being executed in sequence. However, there are times when you might want to skip certain lines of code. This is where the if statement comes in handy.

The if statement is used when you want to execute some code only if a certain condition is met. In larger programs, this condition is something the programmer cannot predict in advance. It might depend on the result of a calculation, data retrieved from a file, or user input. For example, if you write a program that processes experimental results, you might want to print a warning if those results fall outside the expected range. But when you’re writing the program, you won’t know in advance what those results will be.

In small code snippets which we use for CaR exercises, it can be challenging to come up with an example of a condition that isn’t known in advance. So, in the following examples, some conditions might seem obvious. You should keep in mind that the benefit of if statements is most apparent in larger programs, and the goal of these exercises is to help you understand the Python syntax.

Prep 3.1: Basic if statements#

Run the following code and observe what gets printed.

a = 5
if a > 2:
    print("The value of a is greater than two!")
if a < 2: 
    print("The value of a is less than two!") 

Change the first line of the code above to a = 1 and run the code again. Observe what gets printed. Now change the first line of the code to a = 2 and run the code again. Does anything get printed?

Prep 3.2: The anatomy of an if statement#

Consider the following code. Try to predict what will be printed before running the code. Then run the code and observe the output.

a = 5
b = 2
if a > b:
    print("This line prints something.")
    b = a
print("Value of b is", b)

The Reading material explains the syntax and behavior of the if statement. Here is a summary.

Syntax of an if statement:

  • Keyword if indicates the start of the if statement.

  • Keyword if is followed by a condition. The condition is an expression that Python may evaluate to True or False.

  • Colon : indicates the end of the condition and the start of the body of the if statement.

  • The body of the if statement is indented, which usually means the line starts with 4 empty spaces.

  • All indented lines following the if statement are in the body (also known as a code block).

  • The first unindented line after the body is the end of the if statement.

Behavior of an if statement:

  • If the condition is evaluated to True, the body of the if statement is executed.

Take a look at the example above and now identify:

  • the keyword if

  • the condition

  • the body of the if statement.

Prep 3.3: Changing the condition#

In this exercise, you will be modifying the condition in the code above and observing how it affects the output. We are relying on what you have learned about boolean variables in the previous week. Recall that you can construct and combine boolean expressions using:

  • Comparison operators ==, !=, <, >, <=, >=

  • Logical operators and, or, not

Consider the same code as before.

a = 5
b = 2
if a > b:
    print("This line prints something.")
    b = a
print("Value of b is", b)

The expression a > b is the condition of this if statement. Change the condition to:

  • a != b, an expression using the not-equal operator.

    • Change the values of a and b to get the condition to evaluate to True, such that the print statement is executed.

  • (a > 2) and (b > 0), an expression using the logical and operator between two boolean expressions.

    • Change the value of a to be 1. Change the value of b to first -10 and then 10. Is the print statement executed in both cases?

    • Change the values of a and b to get the condition to evaluate to True, such that the print statement is executed.

  • True, the constant boolean expression.

    • Try changing the values of variables a and b. Does this affect the outcome?

  • False, the constant boolean expression.

    • Do the values of variables a and b matter in this case?

The last two conditions are valid expressions, but not very useful since their values are constant. It is, however, very common to use boolean variables as conditions, as we show in the next example.

Prep 3.4: Using boolean variables as conditions#

Consider the following code. Try to predict what will be printed before running the code. Then run the code and observe the output.

height = 2.08
is_tall = height > 2.0

if is_tall:
    print("The person is tall.")

What is the value of the variable is_tall? Add a print statement print(is_tall) after the if statement (outside the body of the if statement) to check the value of the variable is_tall.

Modify the value of the variable height to 1.65. What is the value of the variable is_tall now?

Prep 3.5: The if-else statements#

If you want to execute some code when a condition is met and some other code when the condition is not met, you can add an else clause to an if statement. This is an if-else statement. The Reading material explains the syntax and the behavior of an if-else statement.

Let’s consider the if-else statement below. Try to predict what will be printed before running the code. Then run the code and observe the output.

height = 2.08
if height > 2.0:
    print("The person is tall")
else:
    print("The person is not tall")

Try changing the value of the variable height to 1.65 and observe the output. What is printed in this case?

Prep 3.6: Nested if statements#

If several conditions need to be checked, you can place an if statement inside another if statement. This is a nested if statement. Let’s consider the nested if statement below. Try to predict what will be printed before running the code. Then run the code and observe the output.

pollution_level = 12

if pollution_level > 15:
    print("Pollution level is above normal.")
    if pollution_level > 30:
        print("Pollution level is dangerous!")
else:
    print("Pollution level is within the normal limits.")
    if pollution_level < 0.5:
        print("There is almost no pollution.")

Now:

  • Change the value of the variable pollution_level to 18 and observe the output.

  • Change the value of the variable pollution_level to 40 and observe the output.

  • Change the value of the variable pollution_level to 0.1 and observe the output.

Prep 3.7: The elif clause#

If you have several blocks of code, and you want exactly one block of code to be executed, you can use elif clauses. Consider the code below, which looks similar to the previous example. Try to predict what will be printed before running the code. Then run the code and observe the output.

pollution_level = 12

if pollution_level > 30:
    print("Pollution level is dangerous!")
elif pollution_level > 15:
    print("Pollution level is above normal.")
elif pollution_level > 0.5:
    print("Pollution level is within the normal limits.")
elif pollution_level >= 0:
    print("There is almost no pollution.")
else:
    print("Pollution level is invalid.")

Observe the output when you change the value of the variable pollution_level to each of the following values: 18, 40, 0.1, -6.

Prep 3.8: The flow of control#

When working with conditionals, it is important to understand the order in which the code is executed. For example, in the previous example, when the execution reaches the first condition that is True, the code block associated with that condition is executed, and all remaining conditions will be skipped.

If you are unsure about the order of execution, you can use Python Tutor, a free educational tool to visualize the flow of control. Copy any code from the previous exercises and paste it into Python Tutor. Run the code and observe in which order the lines get executed.

Prep 3.9: Conditionals in use#

Consider the following code. Try to predict what will be printed before running the code. Then run the code and observe the output.

box_height = 1.5
box_width = 1.5

if box_height > box_width:
    print("The box is vertical.")
elif box_height < box_width:
    print("The box is horizontal.")
else:
    print("The box is square.")

Observe the output when you change the value of the variable box_height to each of the following values: 12, 0.8, -2.

It probably makes no sense to have a box with a negative height. It is very common to use conditionals to check if the input data is valid. Run the code below to check if the input data is valid.

box_height = 1.5
box_width = 1.5

if (box_height < 0) or (box_width < 0):
    print("The box dimensions are invalid.")

Try changing the value of the variable box_height to a negative value and observe the output.

Prep 3.10: Comparing strings#

The comparison operator == can be used to compare strings. Consider the following code. Try to predict what will be printed before running the code. Then run the code and observe the output.

abbreviation = "DTU"

if abbreviation == "DTU":
    university = "Technical University of Denmark"
else:
    university = "Unknown"

print(university)

Change the value of abbreviation to "KU" and run the code again.

Can you add an elif clause such that the variable university gets assigned the value "Copenhagen University" when the abbreviation is "KU"?

Change the value of abbreviation to "dtu" and run the code again. In Week 7, you will learn how to fix this (case-insensitive string comparison).

Prep 3.11: Debug syntax errors in conditionals#

Errors in code are called bugs, and fixing errors is called debugging. Debugging is a large part of programming, and something every programmer has to learn, which is difficult even for experienced programmers.

Below are several examples, each containing syntax errors because they violate the basic rules of how an if statement is written. For all the examples below, first try to find the error by reading the code. Then run the code to see what happens. Carefully read the error message. Finally, try to fix the error. We have provided hints for fixing the error, but you should try to fix the error without looking at the hints.

a = 5
if a > 100:
print("A large number")
load = 178
if load > 100:
    print("The load is too large")
   print("Reduce the load and try again")
name = "Alice"
if name == "Bob"
    print("Nice to meet you Bob!")
population_a = 20
population_b = 30
if population_a > population_b:
    print("Population A is greater than population B")
else population_b > population_a:
    print("Population B is greater than population A")
x = 0
if x = 0:
    print("x is equal to 0")
x = 0
if x => 0:
    print("x is greater than or equal to 0")

Prep 3.12: Debug logical errors in conditionals#

Run the following code and observe the output. Change the value of the variable radius to an invalid value, such as -1, and run the code again.

radius = 5
if radius > 0:
    area = 3.14 * radius * radius
else:
    print("The radius is invalid")

print("The area is", area)

When making an assignment in the body of the if statement (or in the body of the else statement), you should consider all cases. In the code above, the variable area is not defined if the condition in the if statement is False. This causes an error if we try to access the variable area later in the code.

Prep 3.13: Predict the output#

For each of the following code snippets, try to predict what will be printed before running the code. Then run the code and observe the output.

if False:
    print("Print 1")
print("Print 2")
if False:
    print("Print 3")
    print("Print 4")
if True:
    print("Print 5")
print("Print 6")
if False:
    if True:
        print("Print 7")
    else:
        print("Print 8")
else:
    print("Print 9")
    if not False:
        print("Print 10")
    print("Print 11")
if False:
    print("Print 12")
elif False:
    if True:
        print("Print 13")
elif True:
    print("Print 14")
else:
    print("Print 15")
if False:
    print("Print 16")
elif False:
    print("Print 17")
if False and not True:
    print("Print 18")
elif False or True:
    if True:
        print("Print 19")
else:
    print("Print 20")

Self quiz#

Question 3.1#

Is anything printed by this code?

a = -1
if 0 > a:
    print('Hello')

Question 3.2#

Which of the following statements most accurately describes what happens in this code, where a is an integer (can be either positive or negative)

if a < 0:
    print('Your variable a is negative')
else:
    print('Your variable a is non-negative')

Question 3.3#

What is the value of a after the following code is run?

a = 12
b = 7 
if a > b:
    a = b

Question 3.4#

Consider the following code, which function does the code correspond to?

if a >= b:
    a = b

Question 3.5#

Which of the following statements most correctly describes what happens when this code is run?

if pressure > max_pressure:
    trouble = True
else: 
    no_trouble = True
print("We are in trouble", trouble)

Question 3.6#

What will be the value of the variable a after the following piece of code is run?

a = 2 
if max(a, 1) > 1:
    a = a - 1 
elif min(a, 1) == 1:
    a = 3
else:
    a = a + 4

Question 3.7#

Determine what will be printed after the following code is run

situation = "good"
pollution_level = 15
if pollution_level >= 15:
    situation = "bad"
if pollution_level <= 20:
    situation = situation + " but not too bad"
else:
    situation = situation + " and we should run for the hills"

print(situation)

Question 3.8#

Which of the following statements on conditionals are correct?

Question 3.9#

What is printed by the following code?

a = 15
if a > 10:
    print("too big")
if a < 5:
    print("too small")
else:
    print("just right")

Question 3.10#

What boolean values (True or False ) should variables a and b take for nothing to be printed by the following code?

if a:
    if not b:
        print("Mango")
else:
    print("Avocado")

Question 3.11#

Will the following code correctly assign the variable pressure_within_normal

max_normal_pressure = 20 
minimum_normal_pressure = 8
current_pressure = 7
if current_pressure < max_normal_pressure:
    pressure_within_normal = True 
else:
    pressure_within_normal = False 

Question 3.12#

You are given the boolean variables downpour and freezing , which represent whether there is precipitation and whether the temperature is below 0 degrees Celsius respectively. Snowing will occur when there is precipitation under freezing conditions. How would you define a new boolean variable is_snowing using conditionals?

Question 3.13#

Which of the following statements are correct on conditionals?

Question 3.14#

This piece of code relies on the integer variable day_number where 0 is Monday, 1 is Tuesday, and so on to 6 being Sunday. Which expression would you replace condition with, such that the message is printed on Wednesday?

if condition:
    print("It is Wednesday.")

Question 3.15#

Which assignment is equivalent to the following lines?

if a > 3:
    c = True
elif b < 5:
    c = True
else:
    c = False

Question 3.16#

Which of the claims about Python syntax is correct?

Question 3.17#

What is stored in the variable my_bool after the code is executed?

my_bool = False
if my_bool:
    my_bool = True

Question 3.18#

To make the syntax correct, what could MISSING_LINE be replaced with?

if n == 3:
    print("Omg, it is 3")
MISSING_LINE
    print("Omg, it is 5")
else:
    print("just a number")

Question 3.19#

What is the smallest (integer) score a student can achieve to get the grade "C"?

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >  60:
    grade = "C"
elif score >  49:
    grade = "D"
else:
    grade = "F"

Question 3.20#

You are given a numeric variable ph_level which represents the acidity of a solution. You want to assign a string to the variable solution_type based on the value of ph_level , i.e. neutral for value of 7, acidic for smaller than 7 and basic for values larger than 7. Which of the code snippets correctly assign the solution type?