All Projects
beginner
Calculator
A simple calculator that performs basic arithmetic operations: addition, subtraction, multiplication, and division.
Features
- Basic arithmetic operations
- User input handling
- Error handling for division by zero
- Loop for continuous calculations
Technologies Used
Python BasicsFunctionsLoopsError Handling
Explanation
This calculator uses a while loop to continuously accept user input. It uses match-case (or if-elif) to determine the operation and performs the calculation. Error handling ensures division by zero is caught gracefully.
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero!"
return a / b
def calculator():
print("=== Python Calculator ===")
print("Operations: +, -, *, /")
print("Type 'quit' to exit\n")
while True:
try:
num1 = input("Enter first number: ")
if num1.lower() == 'quit':
print("Goodbye!")
break
num1 = float(num1)
op = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if op == '+':
result = add(num1, num2)
elif op == '-':
result = subtract(num1, num2)
elif op == '*':
result = multiply(num1, num2)
elif op == '/':
result = divide(num1, num2)
else:
print("Invalid operator!")
continue
print(f"Result: {num1} {op} {num2} = {result}\n")
except ValueError:
print("Please enter valid numbers!\n")
calculator()