Today you will
Store values in variables, ask the user questions, and do the shop's maths, including 16% VAT.
- Create and change variables, and know the difference between text (str), whole numbers (int) and decimals (float).
- Ask the user a question with
input()and convert the answer withint()orfloat(). - Calculate totals and VAT with
+ - * /. - Show money neatly with f-strings, like
f"EC${total:.2f}".
1. Variables
A variable is a name that stores a value. Run this, then change the price and run it again.
# Module 2 - Variables: names that store values
shop_name = "Mama J's Bakery" # a string (text)
price = 5.00 # a float (a number with a decimal point)
qty = 3 # an int (a whole number)
total = price * qty
print(shop_name)
print("3 patties cost EC$", total)
price = 5.50 # variables can change
print("New price:", price)name = "your name"
age = "45"
age2 = 45
is_male = True
bdy_temp = 98.5
print(type(bdy_temp))<class 'float'>WRONG VARIABLE TYPE
name = "your name"
age = "45"
is_male = True
bdy_temp = 98.986
print(age + 1) #Cannot add an integer to a string for a math calcTraceback (most recent call last):
File "<string>", line 6, in <module>
TypeError: can only concatenate str (not "int") to strname = "your name"
age = "45"
is_male = True
bdy_temp = 98.986
print(int(age) + 1) # the string was converted to a number before the calculation was done462. The shop calculator
This asks how many patties, then works out the subtotal, VAT and total. Run it and type a number.
# shop.py - Module 2: the price calculator
price = 5.00
qty = int(input("How many beef patties? ")) # input() gives text; int() turns it into a number
subtotal = price * qty
vat = subtotal * 0.16 # 16% VAT
total = subtotal + vat
print(f"Subtotal: EC${subtotal:.2f}") # :.2f shows 2 decimal places
print(f"VAT 16%: EC${vat:.2f}")
print(f"Total: EC${total:.2f}")2.1. input() and f-string
# using the input() built-in function
name = input("What is your name? ") # ask the user for input (always comes back as text)
age = int(input("How old are you? ")) # input runs first, then int() turns the answer into a number
gender = input("Are you male or female? (male/female): ") #give the user accepted answers to choose from
bdy_temp = 98.986454
print("Hi, I am", name, "- I am", age, "years old and I identify as", gender)
print("I do not have covid, my temp is only", round(bdy_temp, 2))What is your name? alex
How old are you? 45
Are you male or female? (male/female): male
Hi, I am alex - I am 45 years old and I identify as male
I do not have covid, my temp is only 98.99f-string - an f-string is text with gaps you can fill in. Put an f before the opening quote, then put any variable or sum inside { }, and Python swaps it for the value.
name = "Mama J"
price = 5.00
quantity = 2
# put an f before the first " - then put the variable you want inside { }
# and Python swaps the { } for that variable's value
print(f"Welcome to {name}'s Bakery")
# you can do calculations inside the { } too
# :.2f means "show 2 decimal places" - perfect for money
print(f"{quantity} patties cost EC${price * quantity:.2f}")Welcome to Mama J's Bakery
2 patties cost EC$10.00ADDITIONAL - STREAMLIT APP - SNEAK PEEK 2
The same idea as input() and f-strings, but in the browser. Instead of typing answers in the terminal, the user types into boxes on a web page.
# shop_input_app.py - input boxes and f-strings in a Streamlit app
# Run it with: streamlit run shop_input_app.py
import streamlit as st
st.title("Mama J's Bakery")
name = st.text_input("What is your name?") # a text box: gives back a str
qty = st.number_input("How many patties?", min_value=1, value=2, step=1) # a number box: gives back an int
price = 5.00 # float
total = price * qty
st.write(f"Hi {name}! {qty} patties cost EC${total:.2f}")See the browser: type a name, pick a number, e.g.
Hi Alex! 3 patties cost EC$15.00Words to know
| Word | Meaning |
|---|---|
| Variable | A name that stores a value: price = 5.00 |
| str | Text: "Beef Patty" |
| int | A whole number: 3 |
| float | A number with a decimal point: 5.00 |
input() | Asks the user a question and returns their answer as text |
| f-string | Text with values inside: f"Total: {total}" |
Bug hunt
Run this and type 3. It crashes with a TypeError. Read the last line, then fix it.
# BUG HUNT - why does this crash?
# Run it, type 3, and read the last line of the error.
qty = input("How many patties? ")
total = qty * 5.00
print("Total:", total)Hints (open only if stuck)
- What kind of value does
input()give back? - How do you turn text into a whole number?
Practice
Homework 2 (5%): change_calculator.py
A program a cashier could use. 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 2
Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).
Your mission today
Make the robot repeat moves with a loop, decide with if, and use a list of speeds.
Drive a square with a loop
The 4 lines inside the loop run 4 times. 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 2 - Repeat with a for loop: drive a square
for side in range(4): # repeat 4 times
robot.set_motors(50, 50) # drive forward
robot.wait(1000)
robot.set_motors(50, -50) # turn right
robot.wait(400) # tune this number so the turn is a right angle
robot.stop()
print("Square done!")Decide with if, and use a list
Change turbo to False and run it again. What changes?
# Module 2 - Decide with if, and store many values in a list
turbo = True # a boolean: True or False
speed = 50
if turbo:
speed = 100
print("Turbo on!")
robot.set_motors(speed, speed)
robot.wait(1000)
robot.stop()
speeds = [30, 60, 90] # a list of numbers
for s in speeds:
print("Now driving at", s)
robot.set_motors(s, s)
robot.wait(500)
robot.stop()Robot words
| Code | What it means |
|---|---|
for side in range(4): | Repeat the indented lines 4 times |
| Indent | The spaces that put lines inside the loop |
True / False | Booleans: yes or no |
if turbo: | Only run the indented lines if turbo is True |
[30, 60, 90] | A list: many values in one variable |
Challenges
Try one at a time. Change the code, run it, and watch.
# Module 2 - Challenges
# 1. Drive a TRIANGLE: 3 sides, and a bigger turn (try wait(550)).
# 2. Drive the square TWICE without copying the code. Hint: change range(4).
# 3. Set turbo = False. What changes?
# 4. Add 120 to the speeds list. What happens?Build puzzle
Put these lines in order to drive a square. Watch the indents!
robot.stop()
robot.set_motors(50, -50)
for side in range(4):
robot.wait(400)
robot.set_motors(50, 50)
robot.wait(1000)Show the answer
for side in range(4):
robot.set_motors(50, 50)
robot.wait(1000)
robot.set_motors(50, -50)
robot.wait(400)
robot.stop()Challenge puzzle
How many times will the robot say "Beep"?
for i in range(5):
print("Beep")Show the answer
5 times. range(5) gives 0, 1, 2, 3, 4.Quiz 2
Pass with 3 out of 5. Then take it for points in the quiz section of robotics.a3tech.uk.