PYTHON CALCULATOR
I made this small Python calculator just to practice loops, conditions, and error handling. It asks the user to enter two numbers and an operator, and then shows the result. The calculator keeps running in a loop until you type “no” when it asks if you want to continue.
It also handles errors like dividing by zero or entering text instead of numbers, so it doesn’t crash.
ABOUT THE CODE
- Using an infinite loop
I used a while True loop to keep the calculator running until the user says no.
while True:
# calculator code runs here
- Taking input from the user
The calculator asks for two numbers and stores them as floating numbers so it can handle both integers and decimals.
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
- Asking for an operator
After taking the numbers, it asks for which operation to perform.
print("Pick any operation (+, -, *, /, %)")
oper = input("Enter the sign of operation you want to perform: ")
You can choose from +, -, *, /, or %. If you type something else, it’ll ask again for a valid operator.
- Performing the calculation
It checks the operator using simple if-elif statements and performs the required operation.
if oper == '+':
result = num1 + num2
elif oper == '-':
result = num1 - num2
elif oper == '*':
result = num1 * num2
elif oper == '/':
result = num1 / num2
elif oper == '%':
result = num1 % num2
else:
print("Enter a valid operator: (+, -, *, /, %)")
continue
If the operator is invalid, the program skips to the next loop using continue.
- Handling errors
I added try and except blocks to handle common errors like typing letters instead of numbers or dividing by zero.
try:
# main calculator code
except ValueError:
print("Value error! Enter valid numbers.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
This makes the calculator more user-friendly and prevents sudden crashes.
- Asking the user to continue
After showing the result, it asks if you want to do another calculation. If you type “yes”, it runs again. If you type “no”, it stops.
choice = input("Do you want to calculate more? (yes/no): ").lower()
if choice != 'yes':
print("Calculator closed. See you soon!")
break
Using .lower() makes it work even if you type “YES” or “Yes”.
EXAMPLE OUTPUT
Enter the first number: 12
Enter the second number: 3
Pick any operation (+, -, *, /, %)
Enter the sign of operation you want to perform: /
Result: 4.0
Do you want to calculate more? (yes/no): yes
Enter the first number: 10
Enter the second number: 0
Pick any operation (+, -, *, /, %)
Enter the sign of operation you want to perform: /
Division by zero is not allowed.
Do you want to calculate more? (yes/no): no
Calculator closed. See you soon!
SUMMARY
This is just a small beginner project I made while learning Python. It helped me understand how loops, conditions, input handling, and exceptions work together. Pretty simple but good for practicing the basics.