The Task
Build a calculator that:
- Shows a menu with these options: Add, Subtract, Multiply, Divide, Factorial, and Quit.
- Asks the user to choose an option.
- Asks for the numbers it needs and shows the result.
- Keeps showing the menu until the user chooses Quit.
- Handles two special cases: dividing by zero and a negative number for factorial.
- Shows a message if the user enters an invalid option.
What You’ll Use
- Functions with parameters and
return *argsto let theadd()function accept any number of values- Recursion to calculate the factorial
while Truewithbreakto keep the menu runningmatch-caseto handle the menu choiceinput(),int(), andfloat()to take and convert inputifandelsefor the special cases
Expected Output
--- Calculator ---
1. Add
2. Subtract
3. Multiply
4. Divide
5. Factorial
6. Quit
Choose an option (1-6): 1
Enter first number: 5
Enter second number: 3
Result: 8.0
(the menu is shown again)
Choose an option (1-6): 5
Enter a whole number: 5
Result: 120
(the menu is shown again)
Choose an option (1-6): 4
Enter first number: 10
Enter second number: 0
Cannot divide by zero.
(the menu is shown again)
Choose an option (1-6): 6
Goodbye!Try It Yourself First
Here are a few hints:
- Write each operation as its own function, and use
returnto give the result back. add()can use*args.- Factorial needs a base case. Think about which number should stop the recursion.
breakcan be used inside the case for the Quit option to stop the surroundingwhileloop.- Check for division by zero and negative factorial input before calling the function.
Give it a try before you scroll down.
Solution
# Menu-Driven Calculator
def add(*args):
total = 0
for number in args:
total = total + number
return total
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
def factorial(number):
if number == 0:
return 1
return number * factorial(number - 1)
while True:
print("\n--- Calculator ---")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Factorial")
print("6. Quit")
choice = input("Choose an option (1-6): ")
match choice:
case "1":
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Result:", add(a, b))
case "2":
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Result:", subtract(a, b))
case "3":
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Result:", multiply(a, b))
case "4":
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if b == 0:
print("Cannot divide by zero.")
else:
print("Result:", divide(a, b))
case "5":
number = int(input("Enter a whole number: "))
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
print("Result:", factorial(number))
case "6":
print("Goodbye!")
break
case _:
print("Invalid option. Please choose a number from 1 to 6.")How It Works
- Each operation lives in its own function and uses
returnto hand the result back. The menu code decides what to do with it. add(*args)collects any number of values into a tuple and adds them in a loop. The menu calls it with two numbers, but it would work with more.factorial()calls itself with a smaller number each time. When number reaches 0, the base case returns 1 and the recursion stops.while Truekeeps the menu running. Thebreakin the Quit option ends the loop.matchchoice compares the input against each case. The choices are strings like"1"becauseinput()always returns a string.case _catches anything else.- The
divide-by-zeroandnegative-factorialchecks happen before the function is called, so the functions stay simple. float()is used for most numbers, which is why5 + 3shows8.0. Factorial usesint()because it needs a whole number.
Common Mistake
If you forget return in a function:
def subtract(a, b):
a - b
print("Result:", subtract(5, 3))
# Output:
# Result: NoneThe function calculates 2, but never hands it back, so the result is None.
One Limitation
If the user types a letter where a number is expected, the program crashes with a ValueError.
For example: Enter first number: hello
We’ll learn how to handle this properly when we reach error handling.
Challenges
If you want to go further, try these:
- Change the
Addoption to ask for three numbers and pass all three toadd(). - Add a Power option that uses the
**operator. - Add an option that uses a function to return
"Even"or"Odd".
👉 Next tutorial: Python Modules