Here's a simple Python calculator that performs basic arithmetic operations. You can copy and run this code in your Python environment.
print("Welcome to the Simple Calculator!")
operators = {'1': '+', '2': '-', '3': '*', '4': '/'}
operations = {
'1': lambda a, b: a + b,
'2': lambda a, b: a - b,
'3': lambda a, b: a * b,
'4': lambda a, b: a / b
}
while True:
print("\nSelect operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
if choice in operators:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == '4' and num2 == 0:
print("Error: Division by zero")
continue
result = operations[choice](num1, num2)
print(f"Result: {num1} {operators[choice]} {num2} = {result}")
next_calculation = input("Do you want to perform another calculation? (y/n): ").lower()
if next_calculation != 'y':
break
else:
print("Invalid choice. Please select 1-4.")
How to use:
- Run the code in a Python environment.
- Choose an operation (1-4).
- Enter two numbers when prompted.
- The result will be displayed.
- Press
y to continue or n to exit.
Features:
- Handles basic arithmetic operations.
- Checks for division by zero.
- Prompts for valid input if invalid values are entered.
- Allows multiple calculations in a loop.
Example Output:
Welcome to the Simple Calculator!
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 3
Enter first number: 5
Enter second number: 3
Result: 5.0 * 3.0 = 15.0
Do you want to perform another calculation? (y/n): y
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 4
Enter first number: 10
Enter second number: 0
Error: Division by zero
Do you want to perform another calculation? (y/n): n
Let me know if you want to add more features (e.g., exponentiation, square roots, or error handling for other edge cases)!