Below is a simple calculator app written in Python. This program allows users to perform basic arithmetic operations like addition, subtraction, multiplication, and division. It runs in the console and includes error handling for invalid inputs, division by zero, and other issues. The app will continue to run until the user chooses to quit.
Features:
- Supports addition (+), subtraction (-), multiplication (*), and division (/).
- Accepts decimal numbers.
- Handles errors gracefully (e.g., invalid input, division by zero).
- Allows multiple calculations in a loop.
- Users can quit by entering 'q' at any input prompt.
How to Run:
- Save the code in a file, e.g.,
calculator.py.
- Open a terminal or command prompt.
- Run the script using Python:
python calculator.py.
- Follow the on-screen prompts.
Here's the complete code:
# Simple Calculator App in Python
def add(a, b):
"""Add two numbers."""
return a + b
def subtract(a, b):
"""Subtract the second number from the first."""
return a - b
def multiply(a, b):
"""Multiply two numbers."""
return a * b
def divide(a, b):
"""Divide the first number by the second, handling division by zero."""
if b == 0:
return "Error: Division by zero is not allowed."
return a / b
def get_user_input(prompt):
"""Get and validate user input as a number or 'q' to quit."""
while True:
user_input = input(prompt).strip()
if user_input.lower() == 'q':
return 'q' # Signal to quit
try:
return float(user_input) # Convert to float for decimal support
except ValueError:
print("Invalid input. Please enter a number or 'q' to quit.")
def main():
print("Welcome to the Simple Calculator App!")
print("You can perform addition (+), subtraction (-), multiplication (*), or division (/).")
print("Enter 'q' at any prompt to quit.")
while True:
# Get first number
num1 = get_user_input("Enter the first number: ")
if num1 == 'q':
print("Exiting the calculator. Goodbye!")
break # Exit the loop
# Get operator
operator = input("Enter the operator (+, -, *, /): ").strip()
if operator.lower() == 'q':
print("Exiting the calculator. Goodbye!")
break # Exit the loop
# Get second number
num2 = get_user_input("Enter the second number: ")
if num2 == 'q':
print("Exiting the calculator. Goodbye!")
break # Exit the loop
# Perform the operation
if operator == '+':
result = add(num1, num2)
elif operator == '-':
result = subtract(num1, num2)
elif operator == '*':
result = multiply(num1, num2)
elif operator == '/':
result = divide(num1, num2)
else:
result = "Error: Invalid operator. Please use +, -, *, or /."
# Display the result
if isinstance(result, str): # Check if it's an error message
print(result)
else:
print(f"Result: {num1} {operator} {num2} = {result}")
print() # Add a blank line for readability
if __name__ == "__main__":
main()
Explanation of the Code:
- Functions for Operations: Each operation (add, subtract, etc.) is defined as a separate function for clarity and reusability.
- Input Handling: The
get_user_input function ensures that the user enters a valid number or 'q' to quit. It uses a loop to keep asking until valid input is provided.
- Main Loop: The
main function contains a while loop that repeatedly asks for inputs and performs calculations. It checks for 'q' at each step to allow quitting.
- Error Handling:
- If the user enters something that's not a number, it prompts them to try again.
- Division by zero is explicitly checked in the
divide function.
- Invalid operators are caught and reported.
- User Experience: The app provides clear prompts and messages, making it easy to use.
Example Usage:
Welcome to the Simple Calculator App!
You can perform addition (+), subtraction (-), multiplication (*), or division (/).
Enter 'q' at any prompt to quit.
Enter the first number: 10
Enter the operator (+, -, *, /): +
Enter the second number: 5
Result: 10.0 + 5.0 = 15.0
Enter the first number: 20
Enter the operator (+, -, *, /): /
Enter the second number: 0
Error: Division by zero is not allowed.
Enter the first number: q
Exiting the calculator. Goodbye!
This is a basic implementation. If you'd like to add more features (e.g., advanced operations like exponentiation, a GUI, or history of calculations), let me know!