|
| 1 | +# Calculator Program with various functionalities |
| 2 | + |
| 3 | +# Function to add two numbers |
| 4 | +def add(x, y): |
| 5 | + return x + y |
| 6 | + |
| 7 | +# Function to subtract two numbers |
| 8 | +def sub(x, y): |
| 9 | + return x - y |
| 10 | + |
| 11 | +# Function to multiply two numbers |
| 12 | +def multi(x, y): |
| 13 | + return x * y |
| 14 | + |
| 15 | +# Function to divide two numbers |
| 16 | +def div(x, y): |
| 17 | + if y == 0: # Prevent division by zero |
| 18 | + return "Division by zero is not allowed" |
| 19 | + return x / y |
| 20 | + |
| 21 | +# Function to calculate power (x^y) |
| 22 | +def power(x, y): |
| 23 | + return x ** y |
| 24 | + |
| 25 | +# Function to calculate factorial |
| 26 | +def factorial(x): |
| 27 | + factorial = 1 |
| 28 | + if x < 0: # Factorial is not defined for negative numbers |
| 29 | + return "Factorial not defined for negative numbers" |
| 30 | + elif x == 0: # Factorial of 0 is 1 |
| 31 | + return 1 |
| 32 | + else: |
| 33 | + for i in range(1, x + 1): |
| 34 | + factorial *= i # Multiply each number from 1 to x |
| 35 | + return factorial |
| 36 | + |
| 37 | +# Main program loop |
| 38 | +while True: |
| 39 | + # Display menu options |
| 40 | + print("\nMenu:") |
| 41 | + print("1. Add") |
| 42 | + print("2. Subtract") |
| 43 | + print("3. Multiply") |
| 44 | + print("4. Divide") |
| 45 | + print("5. Power") |
| 46 | + print("6. Factorial") |
| 47 | + print("7. Exit") |
| 48 | + |
| 49 | + # User input for choice |
| 50 | + choice = int(input("Enter your choice (1-7): ")) |
| 51 | + |
| 52 | + # Perform the selected operation |
| 53 | + if choice == 1: |
| 54 | + n1 = int(input("Enter first number (n1): ")) |
| 55 | + n2 = int(input("Enter second number (n2): ")) |
| 56 | + print(f"{n1} + {n2} = {add(n1, n2)}") |
| 57 | + elif choice == 2: |
| 58 | + n1 = int(input("Enter first number (n1): ")) |
| 59 | + n2 = int(input("Enter second number (n2): ")) |
| 60 | + print(f"{n1} - {n2} = {sub(n1, n2)}") |
| 61 | + elif choice == 3: |
| 62 | + n1 = int(input("Enter first number (n1): ")) |
| 63 | + n2 = int(input("Enter second number (n2): ")) |
| 64 | + print(f"{n1} * {n2} = {multi(n1, n2)}") |
| 65 | + elif choice == 4: |
| 66 | + n1 = int(input("Enter first number (n1): ")) |
| 67 | + n2 = int(input("Enter second number (n2): ")) |
| 68 | + print(f"{n1} / {n2} = {div(n1, n2)}") |
| 69 | + elif choice == 5: |
| 70 | + n1 = int(input("Enter base number (n1): ")) |
| 71 | + n2 = int(input("Enter power (n2): ")) |
| 72 | + print(f"{n1} ^ {n2} = {power(n1, n2)}") |
| 73 | + elif choice == 6: |
| 74 | + n1 = int(input("Enter a number (n1): ")) |
| 75 | + print(f"{n1}! = {factorial(n1)}") |
| 76 | + elif choice == 7: |
| 77 | + print("Exiting the program. Goodbye!") |
| 78 | + break # Exit the loop |
| 79 | + else: |
| 80 | + print("Invalid choice! Please enter a number between 1 and 7.") |
0 commit comments