CodeBlanks Logo Icon CodeBlanks

Putting it together

Write a working calculator with menu loop.

Putting the calculator together

In the final lesson we combine the calculator. All functions are ready; now we'll add an operator choice. We'll use an if/elif structure to apply the selected operation:

operator = "+"
if operator == "+":
    print(add(a, b))
elif operator == "-":
    print(subtract(a, b))

if/elif tries several conditions in order; the first true block runs. We'll cover this structure in detail in a separate group.

The complete calculator

Now we combine all the pieces. We'll assign an operation to the operator variable and call the related function with if/elif:

operator = "*"
if operator == "+":
    print(add(a, b))
elif operator == "-":
    print(subtract(a, b))
elif operator == "*":
    print(multiply(a, b))
elif operator == "/":
    print(divide(a, b))

This is the skeleton of the calculator. In a real app the operator comes from the user; here we test with a fixed value.

Practice Complete the calculator

All functions are ready. Assign operator = "*". Then use if/elif to compare the four operations in order: + calls add, - calls subtract, * calls multiply, / calls divide, and print the result.

Starter code

main.py
# Calculator - define two numbers
a = 10
b = 5
def add(x, y):
    return x + y
def subtract(x, y):
    return x - y
def multiply(x, y):
    return x * y
def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        return 0
# Choose an operator and perform the operation

Sample solution

main.py
operator = "*"
if operator == "+":
    print(add(a, b))
elif operator == "-":
    print(subtract(a, b))
elif operator == "*":
    print(multiply(a, b))
elif operator == "/":
    print(divide(a, b))

Expected output

50

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which block runs in an if/elif structure?

  • The first true condition's block Correct answer
  • All blocks
  • The last block
  • None

Explanation: if/elif runs the first true condition's block.

2 Complete the operator comparison

Question
if operator ____ "+":
    print(add(a, b))
Answer
if operator == "+":
    print(add(a, b))

Explanation: == is the equality comparison.

3 Match the calculator pieces

Term Meaning
def Function definition
if/elif Operator choice
try/except Error catching
print Printing the result

All lessons in Beginner