Project: Calculator
Combine input, casting and if/elif into a real tool: a calculator that reads two numbers and an operator.
None is Python's value for "no result". Assign it with result = None, test it with result is None, or test for a real result with result is not None.
You can put an if inside another branch. Indent that inner if four spaces, and its body another four spaces.
See it run
typed = "8" a = float(typed) print(a * 2) print(typed * 2)
input() always hands you text. Here typed stands in for what a player typed.
Practice project: calculator
Exercise 1
Read a (float), op, then b (float). The player types 8, *, 5.
Set result for + - * / (use elif) and print it. For division by zero, set result to None and print Cannot divide by zero. For any other operator, set result to None and print Invalid operator.
Exercise 2
Build a café bill calculator. Read integer cups and text size from 3, "large". Use if/elif to set unit_price: small = 2.0, large = 3.5. Unknown sizes set total = None and print Unknown size. Otherwise compute total and print it with 2 decimals.
Exercise 3
Build a group rail-fare calculator. Read zone, integer adults, and integer children from "outer", 2, 3. Use match to choose adult fare: inner = 4, outer = 7. Children pay half. Groups of 5 or more people get 10% off the whole total. Print total with 2 decimals. An unknown zone sets total to None and prints Unknown zone.
Free lesson: use the editor to practice it.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.