fork download
  1. def calculator():
  2. print("Welcome to the Python Calculator!")
  3. print("Select an operation:")
  4. print("1. Addition (+)")
  5. print("2. Subtraction (-)")
  6. print("3. Multiplication (*)")
  7. print("4. Division (/)")
  8. print("5. Exponentiation (^)")
  9. print("6. Modulus (%)")
  10. print("7. Exit")
  11.  
  12. while True:
  13. # Get user input for operation
  14. try:
  15. choice = int(input("\nEnter the number of the operation (1-7): "))
  16. except ValueError:
  17. print("Invalid input! Please enter a number between 1 and 7.")
  18. continue
  19.  
  20. if choice == 7:
  21. print("Thank you for using the calculator. Goodbye!")
  22. break
  23.  
  24. if choice not in range(1, 7):
  25. print("Invalid choice! Please select a valid operation.")
  26. continue
  27.  
  28. # Get numbers from user
  29. try:
  30. num1 = float(input("Enter the first number: "))
  31. num2 = float(input("Enter the second number: "))
  32. except ValueError:
  33. print("Invalid input! Please enter numeric values.")
  34. continue
  35.  
  36. # Perform the selected operation
  37. if choice == 1:
  38. print(f"Result: {num1} + {num2} = {num1 + num2}")
  39. elif choice == 2:
  40. print(f"Result: {num1} - {num2} = {num1 - num2}")
  41. elif choice == 3:
  42. print(f"Result: {num1} * {num2} = {num1 * num2}")
  43. elif choice == 4:
  44. if num2 == 0:
  45. print("Error: Division by zero is not allowed.")
  46. else:
  47. print(f"Result: {num1} / {num2} = {num1 / num2}")
  48. elif choice == 5:
  49. print(f"Result: {num1} ^ {num2} = {num1 ** num2}")
  50. elif choice == 6:
  51. print(f"Result: {num1} % {num2} = {num1 % num2}")
  52.  
  53. if __name__ == "__main__":
  54. calculator()
  55.  
Success #stdin #stdout 0.03s 9968KB
stdin
1
10
20
2
50
30
7
stdout
Welcome to the Python Calculator!
Select an operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Exponentiation (^)
6. Modulus (%)
7. Exit

Enter the number of the operation (1-7): Enter the first number: Enter the second number: Result: 10.0 + 20.0 = 30.0

Enter the number of the operation (1-7): Enter the first number: Enter the second number: Result: 50.0 - 30.0 = 20.0

Enter the number of the operation (1-7): Thank you for using the calculator. Goodbye!