Simple Calculator (Python)
What you'll build
A Python script with a calculate(a, op, b) function supporting +, -, *, / and a CLI that reads two numbers and an operator, then prints the result or an error message.
Goals
- Define a function with multiple parameters
- Use if/elif/else to select the operation
- Guard against division by zero
- Handle unknown operators with a clear message
Prerequisites
- Functions and return values
- if/elif/else statements
- input() and float()
Steps
- 1
Write the calculate function
Define calculate(a, op, b) that branches on op and returns the result. Use if/elif/else for the four operators, and return an error string for unknown ops.
Codedef calculate(a, op, b): if op == "+": return a + b elif op == "-": return a - b elif op == "*": return a * b elif op == "/": if b == 0: return "Cannot divide by zero" return a / b else: return "Unknown operator"Expected result
calculate(4, "+", 5) returns 9; calculate(5, "/", 0) returns the error message.
Hint
Check the zero-division case before performing the division.
- 2
Read input from the user
Ask the user for two numbers and an operator. Convert the numbers with float() so decimal input works; leave the operator as a string.
Codea = float(input("First number: ")) op = input("Operator (+, -, *, /): ") b = float(input("Second number: "))Expected result
Three values read from the user, ready to pass to calculate.
- 3
Call the function and print the result
Pass the inputs to calculate and print the result. Keeping the math in a function means the CLI is just input → call → output.
Coderesult = calculate(a, op, b) print(f"{a} {op} {b} = {result}")Expected result
Entering 4, +, 5 prints "4.0 + 5.0 = 9.0"; entering 5, /, 0 prints the error message.
- 4
Test edge cases
Run the script with a few edge cases: division by zero, an unknown operator, and negative numbers. Confirm each returns a sensible result or message.
Code# Test cases (run mentally or in a REPL) print(calculate(4, "+", 5)) # 9 print(calculate(10, "/", 0)) # Cannot divide by zero print(calculate(3, "%", 2)) # Unknown operator print(calculate(-6, "*", 7)) # -42Expected result
Four lines: 9, the zero-division message, the unknown-operator message, and -42.
- 5
Add input validation & exception handling
Add a try/except block in the main function to handle user input errors, using ValueError to catch illegal conversions. Python's exception handling lets the program degrade gracefully on bad input instead of crashing.
Codedef safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)Expected result
Invalid input (non-number or failed validation) prompts for re-entry; valid input returns the number.
Try it yourself
def calculate(a, op, b):
# TODO: implement +, -, *, / with zero-division and unknown-op guards
pass
# TODO: read a, op, b from input, call calculate, print resultdef calculate(a, op, b):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
if b == 0:
return "Cannot divide by zero"
return a / b
else:
return "Unknown operator"
a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))
result = calculate(a, op, b)
print(f"{a} {op} {b} = {result}")What you learned
You built a function that branches on input, handles two error cases, and wired it to a CLI — the same structure behind most command-line utilities.
Related Resources
Related Lessons
- Functions
Multi-parameter function and return values.
- Conditions
if/elif/else branching used to select the operator.
Related Practice
- Functions Concept
Solidify parameters, return, and the pass-through pattern.
- Conditions Predict
Predict which branch runs for a given input.
Related Tools
- Math Evaluator
Compare your calculator with a full expression evaluator.
Related Cheatsheets
- Python Cheatsheet
Function, conditional, and input syntax reference.
Related Reference
- Python Math
Math module reference.
Related Errors
- Syntax Error
Common Python syntax mistakes.
- Type Error
Operating on incompatible types.
- Indentation Error
Inconsistent indentation.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Related Errors
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
- Syntax Error
Common Python syntax mistakes.
- Type Error
Operating on incompatible types.
- Indentation Error
Inconsistent indentation.