Calculator
Integrate parsing, functions, branching, and intentional error handling.
On this page
The concept
The project separates calculation from interaction. calculate receives two operands and a supported operator, then returns a result. main supplies prepared examples or reads values in interactive mode. Keeping the calculation independent makes it testable without a terminal.
The default demonstrations include success, division by zero, and an unknown operator. These are part of the interface rather than accidental crashes. This small project illustrates how to translate a requirement into explicit branches without evaluating arbitrary user text as Python code.
Worked example
Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.
python3 09_projects/68_calculator/lesson.pyimport sys
def calculate(left, operator, right):
if operator == "+":
return left + right
if operator == "-":
return left - right
if operator == "*":
return left * right
if operator == "/":
if right == 0:
raise ValueError("Cannot divide by zero.")
return left / right
raise ValueError("Only + - * / are supported.")
def main():
samples = [(8, "+", 2), (8, "/", 0), (8, "?", 2)]
if "--interactive" in sys.argv:
try:
left = float(input("First number: "))
operator = input("Operator (+ - * /): ").strip()
right = float(input("Second number: "))
except ValueError:
print("Please enter a valid number.")
return
samples = [(left, operator, right)]
for left, operator, right in samples:
try:
print(left, operator, right, "=", calculate(left, operator, right))
except ValueError as error:
print(error)
if __name__ == "__main__":
main()Trace the result
- calculate uses early returns to select a supported operation.
- The interactive parsing boundary handles numeric conversion failures separately.
- The caller displays either the returned result or a deliberate domain error.
8 + 2 = 10
Cannot divide by zero.
Only + - * / are supported.Line-by-line walkthrough
Line 1: import sys
Load sys (interpreter information and command-line arguments). Importing makes these names available; it is not a call to every function in the module.
Lines 4–15: def calculate(left, operator, right):
Define the function calculate with input names left, operator, right. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Lines 5–6: if operator == "+":
Evaluate operator == '+'. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Line 6: return left + right
Evaluate left + right and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Lines 7–8: if operator == "-":
Evaluate operator == '-'. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Line 8: return left - right
Evaluate left - right and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Lines 9–10: if operator == "*":
Evaluate operator == '*'. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Line 10: return left * right
Evaluate left * right and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Lines 11–14: if operator == "/":
Evaluate operator == '/'. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Lines 12–13: if right == 0:
Evaluate right == 0. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Line 13: raise ValueError("Cannot divide by zero.")
Raise ValueError('Cannot divide by zero.'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.
Line 14: return left / right
Evaluate left / right and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Line 15: raise ValueError("Only + - * / are supported.")
Raise ValueError('Only + - * / are supported.'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.
Lines 18–33: def main():
Define the function main with input names no parameters. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 19: samples = [(8, "+", 2), (8, "/", 0), (8, "?", 2)]
Evaluate [(8, '+', 2), (8, '/', 0), (8, '?', 2)], then bind or update samples with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.
Lines 20–28: if "--interactive" in sys.argv:
Evaluate '--interactive' in sys.argv. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.
Lines 21–27: try:
Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.
Line 22: left = float(input("First number: "))
Evaluate float(input('First number: ')), then bind or update left with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 23: operator = input("Operator (+ - * /): ").strip()
Evaluate input('Operator (+ - * /): ').strip(), then bind or update operator with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 24: right = float(input("Second number: "))
Evaluate float(input('Second number: ')), then bind or update right with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Handler for ValueError: control reaches this suite only for a matching exception from the protected body.
Line 26: print("Please enter a valid number.")
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 27: return
Return None to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Line 28: samples = [(left, operator, right)]
Evaluate [(left, operator, right)], then bind or update samples with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.
Lines 29–33: for left, operator, right in samples:
Obtain each item from samples and bind it to (left, operator, right) before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Lines 30–33: try:
Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.
Line 31: print(left, operator, right, "=", calculate(left, operator, right))
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Handler for ValueError: control reaches this suite only for a matching exception from the protected body.
Line 33: print(error)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Lines 36–37: if __name__ == "__main__":
Enter the program entry point only during direct execution. Importing this module still creates definitions but does not run this guarded workflow.
Line 37: main()
Call main with the displayed arguments. This call may have an effect even when its return value is not assigned.
Common mistake
Do not implement the calculator with eval. Add supported operators explicitly and define their exceptional cases.