DO NOT COPY OR SHARE - A3Tech / NCTI course material for enrolled students only
A3Tech logo

Introduction to Python Programming · A3Tech

Module 3

Today you will

Make the program decide: discounts for big orders, and whether the shop is open.

  1. Use if, elif and else to choose what happens.
  2. Compare values with == != < > <= >=.
  3. Combine conditions with and, or and not.
  4. Indent code blocks correctly and understand the colon at the end of an if line.

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.

true_false.py
qty = 8

print(qty > 6)     # is 8 bigger than 6?
print(qty < 6)     # is 8 smaller than 6?
print(type(qty > 6))
Output
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.

store_answer.py
qty = 8
is_party_order = qty >= 6     # store the True/False answer

print("Party order?", is_party_order)
Output
Party order? True

Deep dive B: comparison operators, one by one

These six symbols ask questions about two values. Each one gives back True or False.

SymbolMeansExampleAnswer
==is equal to5 == 5True
!=is NOT equal to5 != 3True
>is greater than5 > 3True
<is less than5 < 3False
>=is greater than OR equal to5 >= 5True
<=is less than OR equal to4 <= 5True

== (equal to) checks if two values are exactly the same. Works with numbers and text.

equal.py
day = "sunday"
print(day == "sunday")
print(day == "monday")
print(10 == 10.0)      # an int and a float with the same value are equal
Output
True
False
True

!= (not equal to) is the opposite of ==. Useful for "anything except...".

not_equal.py
area = "Kingstown"
print(area != "Kingstown")    # is it somewhere else?
print(area != "Calliaqua")
Output
False
True

> and < (greater / less than) compare sizes. The value itself does NOT count: 6 is not greater than 6.

greater_less.py
qty = 6
print(qty > 6)
print(qty < 10)
Output
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.

or_equal.py
qty = 6
print(qty >= 6)    # 6 counts!
print(qty <= 5)
Output
True
False

Text is case-sensitive. Capital letters make a different value, just like print and Print in Module 1.

case.py
print("Sunday" == "sunday")
print("Sunday".lower() == "sunday")
Output
False
True

Types matter too. The text "5" is never equal to the number 5. Remember: input() always gives text.

types_compare.py
answer = "5"           # what input() would give you
print(answer == 5)     # text vs number
print(int(answer) == 5)
Output
False
True

Deep 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?"
assign_vs_compare.py
price = 5            # store 5 in price
print(price == 5)    # ask: is price equal to 5?
Output
True

Use = inside an if and Python stops you:

single_equals_bug.py
qty = 6
if qty = 6:
    print("Six!")
Output
  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:

  1. the word if
  2. a condition (a True/False question)
  3. a colon : at the end of the line
  4. the indented lines underneath (4 spaces) - this is the block that belongs to the if
if_basic.py
qty = 8

if qty >= 6:
    print("Party order!")          # inside the if (indented)
    print("Thanks for ordering big")

print("Order received")            # outside the if: always runs
Output
Party order!
Thanks for ordering big
Order received

Change qty to 3 and run it again. The two indented lines are skipped, but the last line still runs because it isn't indented.

if_false.py
qty = 3

if qty >= 6:
    print("Party order!")
    print("Thanks for ordering big")

print("Order received")
Output
Order received

Deep 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.

if_else.py
qty = 3

if qty >= 6:
    print("Party order: 10% off!")
else:
    print("No discount today.")
Output
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.

elif_chain.py
qty = 7

if qty >= 12:
    print("15% off")
elif qty >= 6:
    print("10% off")
elif qty == 0:
    print("Nothing ordered")
else:
    print("No discount")
Output
10% off

Order matters! Here the checks are swapped. 15 patties should get 15% off, but qty >= 6 is True first, so Python stops there.

elif_wrong_order.py
qty = 15

if qty >= 6:              # checked first - and 15 >= 6 is True!
    print("10% off")
elif qty >= 12:           # never reached
    print("15% off")
Output
10% off

Deep dive G: and, or, not - combining conditions

and: BOTH sides must be True.

and.py
hour = 10
day = "monday"

print(hour >= 7 and hour < 18)          # between 7am and 6pm?
print(day != "sunday" and hour >= 7)
Output
True
True

or: AT LEAST ONE side must be True.

or.py
day = "saturday"

is_weekend = day == "saturday" or day == "sunday"
print("Weekend?", is_weekend)
Output
Weekend? True

not: flips True to False and False to True.

not.py
is_open = False
print(not is_open)

if not is_open:
    print("Sorry, we're closed.")
Output
True
Sorry, we're closed.
ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse
or_trap.py
day = "monday"

if day == "saturday" or "sunday":     # wrong - always True
    print("Weekend!")

if day == "saturday" or day == "sunday":   # right
    print("Weekend (correct check)")
Output
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().

clean_text.py
day = "  SunDAY "

print(day == "sunday")
clean = day.strip().lower()
print(clean)
print(clean == "sunday")
Output
False
sunday
True

Deep 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
discount_maths.py
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}")
Output
10% off: 54.0
15% off: 51.0
You save: 9.0
You pay: EC$51.00

1. Discounts with if / elif / else

Try 3, 7 and 12 patties. Which line runs each time?

01_discount.py
# 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.

02_opening_hours.py
# 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

WordMeaning
ifRun the indented lines only if the condition is True
elif"Else if": check another condition
elseRuns when none of the conditions were True
==Is equal to (compares). = stores
and / orBoth must be true / at least one must be true
IndentThe 4 spaces that put a line inside an if

Bug hunt

Two mistakes. Fix the first error, run again, then fix the second.

03_indent_bug.py
# BUG HUNT - find the 2 mistakes
qty = 8
if qty >= 6
    print("Party order!")
else:
print("Small order")
Hints (open only if stuck)
  1. What goes at the end of an if line?
  2. 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.

MarkMeans
5Runs and has everything
3Runs with parts missing, or has errors
1Started
0Not submitted

Quiz 3

Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).

1. What does this print?
qty = 7
if qty >= 6:
    print("Party")
else:
    print("Small")
2. What is the difference between = and ==?
3. What does this print?
hour = 20
if hour >= 7 and hour < 18:
    print("Open")
else:
    print("Closed")
4. Which message appears for qty = 15?
if qty >= 6:
    print("10% off")
elif qty >= 12:
    print("15% off")
5. What causes "SyntaxError: expected ':'"?

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
# 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}")
Output
See the browser. Try 0, 3, 7 and 12 patties.