Today you will
Make the program decide: discounts for big orders, and whether the shop is open.
- Use
if,elifandelseto choose what happens. - Compare values with
== != < > <= >=. - Combine conditions with
and,orandnot. - Indent code blocks correctly and understand the colon at the end of an
ifline.
Deep dive A: True and False - what an if actually checks
In Module 2 we met bool: a value that is only ever True or False. Every decision in Python comes down to one of these two answers. A comparison is a question, and Python answers it with True or False.
qty = 8
print(qty > 6) # is 8 bigger than 6?
print(qty < 6) # is 8 smaller than 6?
print(type(qty > 6))True
False
<class 'bool'>So when we later write if qty > 6:, Python first works out qty > 6, gets True, and then decides what to do. You can even store the answer in a variable.
qty = 8
is_party_order = qty >= 6 # store the True/False answer
print("Party order?", is_party_order)Party order? TrueDeep dive B: comparison operators, one by one
These six symbols ask questions about two values. Each one gives back True or False.
| Symbol | Means | Example | Answer |
|---|---|---|---|
== | is equal to | 5 == 5 | True |
!= | is NOT equal to | 5 != 3 | True |
> | is greater than | 5 > 3 | True |
< | is less than | 5 < 3 | False |
>= | is greater than OR equal to | 5 >= 5 | True |
<= | is less than OR equal to | 4 <= 5 | True |
== (equal to) checks if two values are exactly the same. Works with numbers and text.
day = "sunday"
print(day == "sunday")
print(day == "monday")
print(10 == 10.0) # an int and a float with the same value are equalTrue
False
True!= (not equal to) is the opposite of ==. Useful for "anything except...".
area = "Kingstown"
print(area != "Kingstown") # is it somewhere else?
print(area != "Calliaqua")False
True> and < (greater / less than) compare sizes. The value itself does NOT count: 6 is not greater than 6.
qty = 6
print(qty > 6)
print(qty < 10)False
True>= and <= (or equal to) include the value itself. This is why the discount code uses qty >= 6: an order of exactly 6 should get the discount.
qty = 6
print(qty >= 6) # 6 counts!
print(qty <= 5)True
FalseText is case-sensitive. Capital letters make a different value, just like print and Print in Module 1.
print("Sunday" == "sunday")
print("Sunday".lower() == "sunday")False
TrueTypes matter too. The text "5" is never equal to the number 5. Remember: input() always gives text.
answer = "5" # what input() would give you
print(answer == 5) # text vs number
print(int(answer) == 5)False
TrueDeep dive C: = versus == (the classic mistake)
They look alike but do completely different jobs:
=stores a value: "price becomes 5".==asks a question: "is price 5?"
price = 5 # store 5 in price
print(price == 5) # ask: is price equal to 5?TrueUse = inside an if and Python stops you:
qty = 6
if qty = 6:
print("Six!") File "single_equals_bug.py", line 2
if qty = 6:
^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?Deep dive D: if - run this only when...
An if statement runs a block of code only when its condition is True. It has four parts:
- the word
if - a condition (a True/False question)
- a colon
:at the end of the line - the indented lines underneath (4 spaces) - this is the block that belongs to the if
qty = 8
if qty >= 6:
print("Party order!") # inside the if (indented)
print("Thanks for ordering big")
print("Order received") # outside the if: always runsParty order!
Thanks for ordering big
Order receivedChange qty to 3 and run it again. The two indented lines are skipped, but the last line still runs because it isn't indented.
qty = 3
if qty >= 6:
print("Party order!")
print("Thanks for ordering big")
print("Order received")Order receivedDeep dive E: else - otherwise do this
else catches everything the if didn't. It has no condition of its own, just else:. Exactly ONE of the two blocks will run, never both, never neither.
qty = 3
if qty >= 6:
print("Party order: 10% off!")
else:
print("No discount today.")No discount today.Deep dive F: elif - checking more than two options
elif means "else if": if the first condition was False, check this one. Python checks from the top down and runs the first block that is True, then skips all the rest.
qty = 7
if qty >= 12:
print("15% off")
elif qty >= 6:
print("10% off")
elif qty == 0:
print("Nothing ordered")
else:
print("No discount")10% offOrder matters! Here the checks are swapped. 15 patties should get 15% off, but qty >= 6 is True first, so Python stops there.
qty = 15
if qty >= 6: # checked first - and 15 >= 6 is True!
print("10% off")
elif qty >= 12: # never reached
print("15% off")10% offDeep dive G: and, or, not - combining conditions
and: BOTH sides must be True.
hour = 10
day = "monday"
print(hour >= 7 and hour < 18) # between 7am and 6pm?
print(day != "sunday" and hour >= 7)True
Trueor: AT LEAST ONE side must be True.
day = "saturday"
is_weekend = day == "saturday" or day == "sunday"
print("Weekend?", is_weekend)Weekend? Truenot: flips True to False and False to True.
is_open = False
print(not is_open)
if not is_open:
print("Sorry, we're closed.")True
Sorry, we're closed.| A | B | A and B | A or B |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
day = "monday"
if day == "saturday" or "sunday": # wrong - always True
print("Weekend!")
if day == "saturday" or day == "sunday": # right
print("Weekend (correct check)")Weekend!Deep dive H: cleaning up text with .strip() and .lower()
People type things in different ways: Sunday, SUNDAY, sunday with spaces. Before we compare, we clean the text:
.strip()removes spaces from the start and end.lower()turns every letter into lowercase
The dot means "do this to the text". You can chain them: .strip().lower().
day = " SunDAY "
print(day == "sunday")
clean = day.strip().lower()
print(clean)
print(clean == "sunday")False
sunday
TrueDeep dive I: the discount maths
To take a percentage off, multiply by what's left:
- 10% off = you pay 90% =
* 0.90 - 15% off = you pay 85% =
* 0.85 - 20% off = you pay 80% =
* 0.80
subtotal = 60.00
print("10% off:", subtotal * 0.90)
print("15% off:", subtotal * 0.85)
discount = subtotal * 0.15 # the amount saved
print("You save:", discount)
print(f"You pay: EC${subtotal - discount:.2f}")10% off: 54.0
15% off: 51.0
You save: 9.0
You pay: EC$51.001. Discounts with if / elif / else
Try 3, 7 and 12 patties. Which line runs each time?
# shop.py - Module 3: discounts with if / elif / else
price = 5.00
qty = int(input("How many beef patties? "))
subtotal = price * qty
if qty >= 12:
subtotal = subtotal * 0.85
print("Big party order: 15% off!")
elif qty >= 6:
subtotal = subtotal * 0.90
print("Party order: 10% off!")
elif qty == 0:
print("Nothing ordered.")
else:
print("No discount today.")
print(f"You pay: EC${subtotal:.2f}")2. Is the shop open?
Uses comparisons and and. Try 10 on Monday, 20 on Monday, and 10 on Sunday.
# Module 3 - Is the shop open? (comparisons, and, or)
hour = int(input("What hour is it (0-23)? "))
day = input("What day is it? ").strip().lower()
if day == "sunday":
print("Sorry, we're closed on Sundays.")
elif hour >= 7 and hour < 18:
print("We're open! Come in.")
else:
print("We're closed. Open 7am to 6pm.")Words to know
| Word | Meaning |
|---|---|
if | Run the indented lines only if the condition is True |
elif | "Else if": check another condition |
else | Runs when none of the conditions were True |
== | Is equal to (compares). = stores |
and / or | Both must be true / at least one must be true |
| Indent | The 4 spaces that put a line inside an if |
Bug hunt
Two mistakes. Fix the first error, run again, then fix the second.
# BUG HUNT - find the 2 mistakes
qty = 8
if qty >= 6
print("Party order!")
else:
print("Small order")Hints (open only if stuck)
- What goes at the end of an if line?
- Lines inside if and else are indented 4 spaces.
Practice
Homework 3 (5%): delivery.py
Work out a delivery fee. It must:
Submit your .py file and a screenshot of it running, before the next module.
| Mark | Means |
|---|---|
| 5 | Runs and has everything |
| 3 | Runs with parts missing, or has errors |
| 1 | Started |
| 0 | Not submitted |
Quiz 3
Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).
ADDITIONAL - STREAMLIT APP - SNEAK PEEK 3
The same if / elif / else, but on a web page. The logic is identical - only the output changes, and each message gets its own colour.
# discount_app.py - if / elif / else in a Streamlit app
# Run it with: streamlit run discount_app.py
import streamlit as st
st.title("Mama J's Bakery - Party Orders")
price = 5.00
qty = st.number_input("How many beef patties?", min_value=0, value=1, step=1)
subtotal = price * qty
if qty >= 12:
subtotal = subtotal * 0.85
st.success("Big party order: 15% off!")
elif qty >= 6:
subtotal = subtotal * 0.90
st.info("Party order: 10% off!")
elif qty == 0:
st.warning("Nothing ordered.")
else:
st.write("No discount today.")
st.subheader(f"You pay: EC${subtotal:.2f}")See the browser. Try 0, 3, 7 and 12 patties.Your mission today
Use the robot's sensors: drive until you see a wall, choose which way to turn, and count your steps.
Stop at the wall
The loop keeps going while the front sensor says the wall is far away. Test in Python Mode before class and adjust the wait times and the wall distance (20) if the robot turns too far or stops too early.
# Module 3 - Keep going until you see a wall (while loop + sensor)
while robot.get_sensor(0) > 20: # 0 = front sensor. Keep going while the wall is far away
robot.set_motors(50, 50)
robot.wait(100)
robot.stop()
print("Wall ahead! Stopped.")Choose a side
The robot looks left and right and turns towards more space.
# Module 3 - Decide which way to turn (if / else, and)
left = robot.get_sensor(1) # 1 = left sensor
right = robot.get_sensor(2) # 2 = right sensor
if left < 20 and right < 20:
print("Dead end! Turning around")
robot.set_motors(50, -50)
robot.wait(800)
else:
if left > right:
print("More space on the left")
robot.set_motors(-50, 50)
else:
print("More space on the right")
robot.set_motors(50, -50)
robot.wait(400)
robot.stop()Count your steps
while True goes forever, so break is how we get out.
# Module 3 - Count steps and stop with break
steps = 0
while True:
if robot.get_sensor(0) < 20:
break # leave the loop
robot.set_motors(50, 50)
robot.wait(100)
steps = steps + 1
robot.stop()
print("Steps before the wall:", steps)Robot words
| Code | What it means |
|---|---|
robot.get_sensor(0) | How far away the wall in front is (1 = left, 2 = right) |
while | Keep repeating while something is True |
else | What to do if the if was False |
and | Both things must be True |
break | Leave the loop now |
steps = steps + 1 | Add 1 to the count |
Challenges
Try one at a time. Change the code, run it, and watch.
Challenge puzzle
The robot keeps crashing into the wall. Fix the condition.
while robot.get_sensor(0) < 20:
robot.set_motors(50, 50)
robot.wait(100)
robot.stop()Show the answer
Use > instead of <: keep going while the wall is FAR away.
while robot.get_sensor(0) > 20:Build puzzle
Fill in the blank so the robot counts its steps.
steps = 0
while robot.get_sensor(0) > 20:
robot.set_motors(50, 50)
robot.wait(100)
steps = ______
print("Steps:", steps)Show the answer
steps = steps + 1Quiz 3
Pass with 3 out of 5. Then take it for points in the quiz section of robotics.a3tech.uk.