Below is a Python script that simulates a basic calculator with a nice text-based user interface (TUI). The calculator supports addition, subtraction, multiplication, and division. It includes:
- A clear menu for selecting operations.
- Input validation to handle invalid numbers or choices.
- Error handling for cases like division by zero.
- A loop that keeps the calculator running until the user chooses to exit.
- Formatted output for better readability.
The script uses simple console-based interactions, making it easy to use in a terminal.
def display_menu():
"""Display the main menu for the calculator."""
print("\n" + "=" * 40)
print(" Welcome to the Basic Calculator!")
print("=" * 40)
print("Please choose an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
print("=" * 40)
def get_user_choice():
"""Get the user's choice from the menu."""
while True:
try:
choice = input("Enter your choice (1-5): ").strip()
if choice in ['1', '2', '3', '4', '5']:
return choice
else:
print("Invalid choice. Please enter a number between 1 and 5.")
except Exception as e:
print(f"An error occurred: {e}. Please try again.")
def get_number(prompt):
"""Get a numeric input from the user with validation."""
while True:
try:
return float(input(prompt).strip())
except ValueError:
print("Invalid input. Please enter a valid number.")
def perform_operation(choice, num1, num2):
"""Perform the selected operation."""
if choice == '1':
return num1 + num2 # Addition
elif choice == '2':
return num1 - num2 # Subtraction
elif choice == '3':
return num1 * num2 # Multiplication
elif choice == '4':
if num2 != 0:
return num1 / num2 # Division
else:
print("Error: Division by zero is not allowed.")
return None
def main():
"""Main function to run the calculator."""
while True:
display_menu()
choice = get_user_choice()
if choice == '5':
print("\nThank you for using the Basic Calculator. Goodbye!")
break # Exit the program
num1 = get_number("Enter the first number: ")
num2 = get_number("Enter the second number: ")
result = perform_operation(choice, num1, num2)
if result is not None:
print(f"\nResult: {num1} {['+', '-', '*', '/'][int(choice)-1]} {num2} = {result}")
input("\nPress Enter to continue...") # Pause before returning to menu
if __name__ == "__main__":
main()
How to Run the Script:
- Save the code to a file, e.g.,
basic_calculator.py.
- Open a terminal or command prompt.
- Navigate to the directory containing the file.
- Run the script using Python:
python basic_calculator.py.
Features and Explanation:
- Menu Display: The
display_menu() function prints a formatted menu with separators for a clean look.
- User Input Handling:
get_user_choice() ensures the user enters a valid menu option (1-5).
get_number() validates that the inputs are numbers (handles integers and floats).
- Operations: Performed in
perform_operation(). It checks for division by zero and returns None if an error occurs.
- Result Display: Shows the operation and result in a readable format, e.g., "2.0 + 3.0 = 5.0".
- Loop and Exit: The program loops back to the menu after each operation. Choose "5" to exit gracefully.
- Error Handling: Catches invalid inputs and provides user-friendly messages.
- Pause Feature: After each calculation, it waits for the user to press Enter, improving usability.
This script is simple, robust, and easy to extend if you want to add more features like exponentiation or memory functions. Let me know if you'd like any modifications!