webbersof

Calculator

Aug 27th, 2023
1,473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. def exit_condition():
  2.     return 'Thank you for using the calculator. Goodbye!'
  3.  
  4. def invalid_condition():
  5.     return 'Invalid input. Please try again.'
  6.  
  7. def error_statement():
  8.     return 'Error: Cannot divide by zero!'
  9.  
  10. def comparing(x, y):
  11.     if x > y:
  12.         return f'{x} > {y}'
  13.     elif x < y:
  14.         return f'{x} < {y}'
  15.     else:
  16.         return f'{x} = {y}'
  17.  
  18. def _execute_operation(choice, x, y):
  19.     operations = {
  20.         "1": lambda: x + y,
  21.         "2": lambda: x - y,
  22.         "3": lambda: x * y,
  23.         "4": lambda: x / y if y != 0 else error_statement(),
  24.         "5": lambda: x ** y,
  25.         "6": lambda: x % y if y != 0 else error_statement(),
  26.         "7": lambda: comparing(x, y),
  27.     }
  28.     return operations[choice]()
  29.  
  30. def calculator():
  31.     print("Welcome to the Advanced Calculator!")
  32.  
  33.     while True:
  34.         print("\nSelect an operation:")
  35.         print("1. Addition")
  36.         print("2. Subtraction")
  37.         print("3. Multiplication")
  38.         print("4. Division")
  39.         print("5. Grading")
  40.         print("6. Modulo")
  41.         print("7. Comparing")
  42.         print("8. Exit")
  43.  
  44.         choice = input("Enter the operation number (1/2/3/4/5/6/7/8): ")
  45.  
  46.         if choice == "8":
  47.             print(exit_condition())
  48.             break
  49.         elif choice not in ("1", "2", "3", "4", "5", "6", "7"):
  50.             print(invalid_condition())
  51.             continue
  52.  
  53.         num1 = float(input("Enter the first number: "))
  54.         num2 = float(input("Enter the second number: "))
  55.  
  56.         operation_result = _execute_operation(choice, num1, num2)
  57.         print(f"Result: {operation_result}")
  58.  
  59. if __name__ == "__main__":
  60.     calculator()
  61.  
Advertisement
Add Comment
Please, Sign In to add comment