time_on_phone = 20
if time_on_phone > 15:
print("Warning: you have been on your phone for too long!")Warning: you have been on your phone for too long!
Normally, Python executes instructions from top to bottom. Flow control allows a program to choose which instructions to execute.
For example, an app could warn you if you have spent too much time on your phone:
time_on_phone = 20
if time_on_phone > 15:
print("Warning: you have been on your phone for too long!")Warning: you have been on your phone for too long!
time_on_phone = 10
if time_on_phone > 15:
print("Warning: you have been on your phone for too long!")
# Nothing is printed because the condition is FalseTo make decisions, Python needs questions whose answers are either True or False.
Comparison operators allow us to compare values, variables, or expressions.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | x == 3 |
!= |
Not equal to | x != 3 |
< |
Less than | x < 3 |
> |
Greater than | x > 3 |
<= |
Less than or equal to | x <= 3 |
>= |
Greater than or equal to | x >= 3 |
The double equals sign == compares two values. The single equals sign = assigns a value to a variable.
Open a new Python notebook and run the following snippets. Remember that you can copy code using the button at the top-right of each cell and run it using the button at the top-left.
x = 3
y = 2
# Are x and y equal?
print(x == y)False
# Are x and y different?
print(x != y)True
Comparisons return either True or False. These two values are called Booleans.
# Is x greater than y?
print(x > y)True
Comparison operators do not distinguish between equivalent integers and floats.
x = 3
y = 3.0
print(x == y)True
We can store the result of a comparison in a variable:
temperature = 38
fever = temperature >= 38
print(fever)True
Predict whether each expression is True or False. Check your answers in Python afterward.
7 > 4
7 == 7.0
5 != 5
3 <= 3
10 < 2True
True
False
True
False
Comparison operators care about the types of the values being compared. A string and a number are different values.
x = 3
y = "3"
print(x == y)False
We can compare two strings too.
x = "hi"
y = "hello"
print(x == y)False
String comparison is case-sensitive. Two strings are equal only when their contents and capitalization match exactly.
x = "hi"
y = "HI"
print(x == y)False
Python can also order strings. It compares them lexicographically, one character at a time. Capitalization affects this ordering.
x = "hello"
y = "hola"
print(x > y)False
A secret code is stored as the string "Python". Create a variable called attempt and compare it with the secret code.
Try the values "Python", "python", and "Python ". Explain why only one of them matches.
secret_code = "Python"
attempt = "Python"
print(attempt == secret_code)True
The comparison is case-sensitive, and spaces are characters too. Therefore, "python" and "Python " do not equal "Python".
if StatementThe if statement executes a block of code only when a condition is True. It lets a program make a decision.
if <condition>:
<code to run if the condition is True>Pay special attention to the colon and indentation. The indentation determines which instructions belong to the if statement.
<this instruction always runs>
if <condition>:
<this instruction runs only if the condition is True>
<this instruction always runs>For instance, let us write code that changes any number below 5 into 5.
x = 2
# If x is lower than 5, change it to 5
if x < 5:
x = 5
print(x)5
Create a numeric variable called years. Print I am X years old, where X is the value stored in years, but only if years is positive.
years = 5
if years > 0:
print(f"I am {years} years old")I am 5 years old
Try changing years to a negative number. The program should print nothing.
What happens if years contains a string? The comparison raises an error because Python cannot order a string and an integer.
A robot has a variable called battery. If the battery is at or below 20, print Low battery: return to base. Regardless of the battery level, print Status check complete afterward.
Try your program with battery = 15 and battery = 80.
battery = 15
if battery <= 20:
print("Low battery: return to base")
print("Status check complete")Low battery: return to base
Status check complete
Fix the following code blocks.
# Print the square root of a number only if it is positive
x = 4
if x >= 0:
print(f"The square root of {x} is {x ** 0.5}")# Replace a number by its square if the original is even
x = 4
if x % 2 = 0
x = x ** 2
print(x)# Print "Hello" if a name has more than three letters
name = "John"
if name > 3:
print("Hello")The first block needs indentation. The second uses = instead of == and is missing a colon. The third compares a string with a number instead of checking the length of the string.
x = 4
if x >= 0:
print(f"The square root of {x} is {x ** 0.5}")The square root of 4 is 2.0
x = 4
if x % 2 == 0:
x = x ** 2
print(x)16
name = "John"
if len(name) > 3:
print("Hello")Hello
else StatementThe else statement provides an alternative. Its block executes when the if condition is False.
if <condition>:
<code to run if the condition is True>
else:
<code to run if the condition is False>Only one of the two branches executes.
<this instruction always runs>
if <condition>:
<one branch runs>
else:
<the other branch runs>
<this instruction always runs># Check whether a student passed an exam
# Assume that the mark is between 0 and 10
grade = 7
if grade >= 5:
print("You passed")
else:
print("You have not passed")You passed
Write a program that reports whether a number is even or odd.
x = 7
if x % 2 == 0:
print("x is even")
else:
print("x is odd")x is odd
A player can open a door only when the Boolean variable has_key is True. Print The door opens if the player has the key. Otherwise, print The door is locked.
Test both possible values of has_key.
has_key = False
if has_key:
print("The door opens")
else:
print("The door is locked")The door is locked
For each code cell, decide whether it prints a message or raises an error. If it prints something, write the exact output.
name = "Alberto"
if "a" in name:
print("The name contains the letter a")
else:
print("The name does not contain the letter a")x = 9
if x % 3 == 0:
print("x is divisible by 3")
else
print("x is not divisible by 3")x = 5
y = x < 0
if y:
print("x is negative")
else:
print("x is zero or positive")The first block prints The name does not contain the letter a. The search is case-sensitive, and Alberto contains uppercase A, not lowercase a.
The second block raises a syntax error because else is missing a colon.
The third block prints x is zero or positive. The comparison 5 < 0 produces False, so the else branch runs.
elif StatementSometimes a program must choose between more than two possibilities. The elif keyword, short for “else if,” checks another condition when the preceding conditions were False.
if <condition1>:
<code if condition1 is True>
elif <condition2>:
<code if condition2 is True>
else:
<code if no earlier condition is True>Python checks the conditions from top to bottom and executes the first branch whose condition is True. After selecting a branch, it skips the rest of the chain.
x = -5
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")x is negative
We can chain several elif clauses:
x = -10
if x > 10:
print("x is greater than 10")
elif x > 0:
print("x is positive")
elif x < -5:
print("x is lower than -5")
elif x < 0:
print("x is negative")
else:
print("x is zero")x is lower than -5
The order matters. An early condition can capture a value before Python reaches a later, more specific condition.
Which branch can never execute, regardless of the value of x?
if x > 10:
print("greater than 10")
elif x > 0:
print("positive")
elif x < 0:
print("negative")
elif x < -5:
print("lower than -5")
else:
print("zero")The branch elif x < -5 can never execute. Every number below -5 already satisfies the earlier condition x < 0.
Put the more specific condition first:
x = -10
if x > 10:
print("greater than 10")
elif x > 0:
print("positive")
elif x < -5:
print("lower than -5")
elif x < 0:
print("negative")
else:
print("zero")lower than -5
Calculate a ticket price from a visitor’s age:
Store the result in price, then print it. Test at least one age from every category.
age = 20
if age < 4:
price = 0
elif age <= 12:
price = 8
elif age <= 64:
price = 15
else:
price = 10
print(f"Ticket price: €{price}")Ticket price: €15
After the first condition fails, Python already knows that age >= 4. We do not need to repeat that comparison in the second condition.
Write a program that calculates the following function:
\[ f(x) = \begin{cases} x^2, & x < 0, \\ 2x + 1, & 0 \leq x < 3, \\ 7, & x \geq 3. \end{cases} \]
Store the result in fx and print it. Test x = -2, x = 1, and x = 5.
x = 1
if x < 0:
fx = x ** 2
elif x < 3:
fx = 2 * x + 1
else:
fx = 7
print(fx)3
Logical operators combine or modify Boolean conditions.
andThe and operator returns True only when both conditions are True.
if <condition1> and <condition2>:
<code to run if both conditions are True># A student passes only with a sufficient grade and attendance
grade = 8
attendance = 89
if grade >= 5 and attendance >= 80:
print("You passed")
else:
print("You have not passed")You passed
orThe or operator returns True when at least one condition is True.
if <condition1> or <condition2>:
<code to run if either condition is True>grade = 8
attendance = 89
if grade < 5 or attendance < 80:
print("You have not passed")
else:
print("You passed")You passed
notThe not operator reverses a Boolean value. not True is False, and not False is True.
if not <condition>:
<code to run if the condition is False># Add a period if the string does not already end with one
s = "Hello world"
if not s.endswith("."):
s = s + "."
print(s)Hello world.
Write a sentence containing the word cat and store it in sentence. Replace cat with dog, but only if both love and cat appear in the sentence.
sentence = "I love cats"
if "love" in sentence and "cat" in sentence:
sentence = sentence.replace("cat", "dog")
print(sentence)I love dogs
A spacecraft may launch only when all three conditions are met:
fuel is at least 80.weather equals "clear".crew_ready is True.Print Launch approved when all conditions are met. Otherwise, print Launch delayed.
fuel = 95
weather = "clear"
crew_ready = True
if fuel >= 80 and weather == "clear" and crew_ready:
print("Launch approved")
else:
print("Launch delayed")Launch approved
Given coordinates x and y, report the point’s quadrant:
x > 0 and y > 0x < 0 and y > 0x < 0 and y < 0x > 0 and y < 0If either coordinate equals zero, print The point is on an axis.
x = -2
y = 5
if x > 0 and y > 0:
print("Quadrant I")
elif x < 0 and y > 0:
print("Quadrant II")
elif x < 0 and y < 0:
print("Quadrant III")
elif x > 0 and y < 0:
print("Quadrant IV")
else:
print("The point is on an axis")Quadrant II
We can place one if statement inside another. This is useful when the second decision matters only after the first condition is satisfied.
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("You may enter")
else:
print("You need a ticket")
else:
print("You must be at least 18")You may enter
The inner condition is checked only when age >= 18 is True.
A player finds a treasure chest. The chest opens only if has_key is True. If it opens, the player receives the treasure only if inventory_space > 0.
Print one of these messages:
The chest is lockedYour inventory is fullTreasure collected!Use one if statement inside another.
has_key = True
inventory_space = 2
if has_key:
if inventory_space > 0:
print("Treasure collected!")
else:
print("Your inventory is full")
else:
print("The chest is locked")Treasure collected!
Nested conditions are valid, but they are not always necessary. When two requirements lead to the same result, a logical operator may be clearer:
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("You may enter")
else:
print("Entry denied")You may enter
The regular indented form should be your default. Python also supports shorter forms that you may encounter in other people’s code.
if StatementsAn entire if statement can appear on one line:
if <condition>: <code># Change negative numbers to 0
num = -3
if num < 0: num = 0
print(num)0
Python also permits several instructions separated by semicolons, but this usually makes code harder to read. Prefer the indented form in this course.
A conditional expression selects one of two values:
<expression1> if <condition> else <expression2># Format values below 100 with two decimals
# Format values of 100 or more with no decimals
num = 99
out = f"{num:.2f}" if num < 100 else f"{num:.0f}"
print(out)99.00
Conditional expressions can be readable for short assignments. Use a normal if and else when the decision requires several instructions or is difficult to understand at a glance.
A delivery drone uses three variables:
distance = 8
battery = 65
weather = "clear"Apply these rules in order:
"storm", the drone cannot fly.Print exactly one of these messages:
Flight cancelled: stormRecharge requiredDelivery approvedInsufficient battery for this distanceTest your program with several combinations. Try to make every possible message appear.
distance = 8
battery = 65
weather = "clear"
if weather == "storm":
print("Flight cancelled: storm")
elif battery < 20:
print("Recharge required")
elif distance > 10 and battery >= 60:
print("Delivery approved")
elif distance <= 10 and battery >= 30:
print("Delivery approved")
else:
print("Insufficient battery for this distance")Delivery approved
For each concept, explain its purpose in one sentence:
if statementelse branchelif branchand, or, and not operatorsThen answer: why can an if statement make a decision but not repeat an action?
When you feel ready, test your knowledge using the review exercises.
Work through the “Flow Control” homework exercises available here. To earn participation credit, complete the exercises highlighted in red.
We will learn about loops. They allow programs to repeat instructions and process several values without writing the same code again and again.
See you!