Okay, here's a Python code for a simple command-line calculator app. It includes basic operations (add, subtract, multiply, divide) and some error handling.
python
def add(x, y):
"""Adds two numbers and returns the sum."""
return x + y
def subtract(x, y):
"""Subtracts the second number from the first and returns the difference."""
return x - y
def multiply(x, y):
"""Multiplies two numbers and returns the product."""
return x * y
def divide(x, y):
"""Divides the first number by the second. Handles division by zero."""
if y == 0:
return "Error! Division by zero is not allowed."
return x / y
def calculator():
"""
Runs a simple command-line calculator application.
Allows users to perform basic arithmetic operations repeatedly.
"""
print("-----------------------------------")
print(" Simple Console Calculator")
print("-----------------------------------")
while True:
print("\nSelect 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 calculator. Goodbye!")
break
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter valid numbers.")
continue # Go back to the start of the loop
result = None # Initialize result to None
if choice == '1':
result = add(num1, num2)
operation_symbol = '+'
elif choice == '2':
result = subtract(num1, num2)
operation_symbol = '-'
elif choice == '3':
result = multiply(num1, num2)
operation_symbol = '*'
elif choice == '4':
result = divide(num1, num2)
operation_symbol = '/'
# Check if the result is an error message (from divide by zero)
if isinstance(result, str) and "Error!" in result:
print(result)
else:
print(f"{num1} {operation_symbol} {num2} = {result}")
else:
print("Invalid choice. Please enter a number between 1 and 5.")
# Run the calculator application
if __name__ == "__main__":
calculator()
How to Run the Code:
Save: Save the code into a file named calculator.py (or any other .py extension).
Open Terminal/Command Prompt: Navigate to the directory where you saved the file.
Execute: Run the command: python calculator.py
Features and Explanation:
Functions for Operations:
add(x, y): Takes two numbers and returns their sum.
subtract(x, y): Takes two numbers and returns their difference.
multiply(x, y): Takes two numbers and returns their product.
divide(x, y): Takes two numbers and returns their quotient. It includes a check to prevent ZeroDivisionError.
calculator() Function (Main Logic):
Welcome Message: Prints a nice header.
while True Loop: Keeps the calculator running indefinitely until the user chooses to exit.
Menu Display: Presents the available operations (Add, Subtract, Multiply, Divide, Exit).
User Input (choice): Prompts the user to select an operation.
Exit Condition: If choice is '5', it prints an exit message and uses break to exit the while loop, ending the program.
Number Input (num1, num2):
It uses float(input(...)) to allow for decimal numbers.
Error Handling (try-except ValueError): If the user enters non-numeric input (e.g., "hello" instead of "10"), it catches the ValueError, prints an error message, and continues to the next iteration of the while loop (asking for an operation again).
Perform Calculation:
An if/elif chain checks the choice and calls the appropriate function (add, subtract, etc.).
It stores the result and the operation_symbol for cleaner output.
Display Result:
It specifically checks if the result is a string (which would be the "Error! Division by zero" message). If it is, it prints the error message directly.
Otherwise, it prints the calculation in a user-friendly format (e.g., "10.0 + 5.0 = 15.0").
Invalid Choice: If the choice is not one of the valid options (1-5), it prints an "Invalid choice" message.
This is a standard Python idiom. It ensures that the calculator() function is called only when the script is executed directly (not when it's imported as a module into another script).