Lab Activity: Building Calculator
Objectives
-
Practice using conditional statements (if/elif/else).
-
Use a while loop to keep repeating tasks until exit.
-
Apply break and continue for loop control.
-
Build a simple menu-driven calculator program.
-
Handle errors such as invalid input and division by zero.
step-by-step instructions
Step 1: Plan the Menu
Menu Options:
-
Add two numbers
-
Subtract two numbers
-
Multiply two numbers
-
Divide two numbers
-
Exit the program
Step 2: Code the Loop and Menu
We’ll use while True: so the menu repeats until the user selects “Exit”.
def run_calculator():
while True:
# Display menu
print("Select an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter choice (1/2/3/4/5): ")
if choice == '5':
print("Exiting the calculator.")
break
Step 3: Handle User Input
Add input for numbers and perform operations:
elif choice in ('1', '2', '3', '4'):
try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numbers only.")
continue
if choice == '1':
print("Result:", a + b)
elif choice == '2':
print("Result:", a - b)
elif choice == '3':
print("Result:", a * b)
elif choice == '4':
if b == 0:
print("Error: Division by zero is not allowed.")
else:
print("Result:", a / b)
Step 4: Handle Invalid Choices
If the user enters something not in the menu:
else:
print("Invalid choice. Please enter a number between 1 and 5.")
Complete Program
def run_calculator():
while True:
# Display menu
print("nSelect an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter choice (1/2/3/4/5): ")
if choice == '5':
print("Exiting the program. Goodbye!")
break
elif choice in ('1', '2', '3', '4'):
try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numbers only.")
continue
if choice == '1':
print("Result:", a + b)
elif choice == '2':
print("Result:", a - b)
elif choice == '3':
print("Result:", a * b)
elif choice == '4':
if b == 0:
print("Error: Division by zero is not allowed.")
else:
print("Result:", a / b)
else:
print("Invalid choice. Please enter a number between 1 and 5.")
run_calculator()
Sample Interaction
Select an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice (1/2/3/4/5): 1
Enter first number: 10
Enter second number: 25
Result: 35.0
Enter choice (1/2/3/4/5): 4
Enter first number: 10
Enter second number: 0
Error: Division by zero is not allowed.
Enter choice (1/2/3/4/5): 9
Invalid choice. Please enter a number between 1 and 5.
Enter choice (1/2/3/4/5): 5
Exiting the program. Goodbye!
Key Concepts Learned
-
Using while True for looping until exit.
-
Handling decisions with if/elif/else.
-
Using break and continue effectively.
-
Building a user-friendly, interactive program.
