The shop register
It adds up prices and takes away the money you pay.
12GAME PROJECTS · CALCULATOR
You type two numbers and a sign. PyBot picks the right math and shows the answer.
IN REAL LIFE
Many machines take numbers, choose an operation, and show a result.
It adds up prices and takes away the money you pay.
8 slices for 4 friends: divide, and each one gets 2.
Type 0 after the ÷ sign and it shows a message, not an answer.
THE PLAN
Each step uses something you already know.
Turn each answer into a number. float keeps decimals like 2.5.
input + float
The player types +, -, * or /. It stays text.
input
Compare the sign with == and do the matching operation.
if / elif / else
calculate gets the numbers and the sign and returns the answer. It checks for 0 first.
def + return
RUN IT
Guess first. Then run real Python and check.
a = float(input("First number? "))
sign = input("Sign (+ - * /)? ")
b = float(input("Second number? "))
print("Answer:", calculate(a, sign, b))PyBot's answers: 8, then *, then 2
What is the last line?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Change the answers to 7, / and 0. What does PyBot say?
BUILD IT
Fix one part at a time. Run after each step.
8 + 2 shows 82. Turn both answers into numbers with float().
First number? 8 Second number? 2 Sum: 10.0OUTPUT
The calculator knows + and -, but not *. Add an elif for * before else.
First number? 6 Sign (+ - * /)? * Second number? 7 Answer: 42.0OUTPUT
Dividing by 0 stops the program with an error. Make divide return the message when b is 0.
Answer: 4.0 Answer: Oops! You can't divide by 0.OUTPUT
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
a = input("First number? ")
b = input("Second number? ")
print(a + b)PyBot's answers: 3, then 4
What does the last line show?
if sign == "+":
print(a + b)
elif sign == "-":
print(a - b)
else:
print("?")a is 9.0, b is 4.0 and sign is "-"
What will Python show?
Which line is right?
if b == 0:
return "Oops! You can't divide by 0."
return a / bWhy does the calculator check b first?
print("Answer:", calculate(8, "*", 2))calculate ends with return a * b. Where does the 16 go?
What does PyBot answer?
print(7 / 2)What will Python show?
Want a fresh start? Clear only this page.
Numbers and a sign go in, if/elif picks the math, and return sends the answer out. Check for 0 before you divide.