gruntfutuk

simple calculator with menu

Aug 25th, 2025
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.94 KB | None | 0 0
  1. import math
  2. import operator
  3.  
  4. # Use a dictionary to define the menu of operations.
  5. # Structure: key: (description, function, number_of_arguments, symbol)
  6. OPERATIONS = {
  7.     '1': ("Add", operator.add, 2, '+'),
  8.     '2': ("Subtract", operator.sub, 2, '-'),
  9.     '3': ("Multiply", operator.mul, 2, '*'),
  10.     '4': ("Divide", operator.truediv, 2, '/'),
  11.     '5': ("Power", operator.pow, 2, '**'),
  12.     '6': ("Square Root", math.sqrt, 1, '√'),
  13.     '7': ("Exit", None, 0, None)
  14. }
  15.  
  16. def get_operands(num_args: int) -> list[float]:
  17.     """Prompts the user for the required number of operands and validates them."""
  18.     operands = []
  19.     for i in range(num_args):
  20.         while True:
  21.             try:
  22.                 prompt = f"Enter the {i + 1}{'st' if i == 0 else 'nd' if i == 1 else 'rd' if i == 2 else 'th'} number: "
  23.                 if num_args == 1:
  24.                     prompt = "Enter the number: "
  25.                 num = float(input(prompt))
  26.                 operands.append(num)
  27.                 break
  28.             except ValueError:
  29.                 print("Invalid input. Please enter a number.")
  30.     return operands
  31.  
  32. def present_menu(operations: dict) -> str:
  33.     """Displays the menu of options and returns a validated user choice."""
  34.     print("\nSelect operation.")
  35.     for key, (description, _, _, _) in operations.items():
  36.         print(f"{key}. {description}")
  37.  
  38.     while True:
  39.         choice = input(f"Enter choice ({', '.join(operations.keys())}): ")
  40.         if choice in operations:
  41.             return choice
  42.         else:
  43.             print("Invalid choice. Please select a valid option.")
  44.  
  45. def main():
  46.     """Main function to run the calculator."""
  47.     while True:
  48.         choice = present_menu(OPERATIONS)
  49.         description, operation_func, num_args, symbol = OPERATIONS[choice]
  50.  
  51.         if operation_func is None:  # Exit condition
  52.             print("bye")
  53.             break
  54.  
  55.         operands = get_operands(num_args)
  56.  
  57.         # Add error handling for specific operations
  58.         if operation_func == operator.truediv and operands[1] == 0:
  59.             print("Error: Cannot divide by zero.")
  60.         elif operation_func == math.sqrt and operands[0] < 0:
  61.             print("Error: Cannot take the square root of a negative number.")
  62.         else:
  63.             result = operation_func(*operands)
  64.             # Format the output string based on the operation
  65.             if num_args == 2:
  66.                 print(f"{operands[0]} {symbol} {operands[1]} = {result}")
  67.             elif num_args == 1:
  68.                 print(f"{symbol}{operands[0]} = {result}")
  69.  
  70.         # Ask user if they want to continue
  71.         while True:
  72.             next_calc = input("Continue? (y/n): ").lower()
  73.             if next_calc in ('y', 'n'):
  74.                 break
  75.             else:
  76.                 print("Invalid input, Enter y or n.")
  77.  
  78.         if next_calc == 'n':
  79.             print("bye")
  80.             break
  81.  
  82. if __name__ == "__main__":
  83.     main()
  84.  
Advertisement
Add Comment
Please, Sign In to add comment