|
| 1 | +def add(x, y): |
| 2 | + """This function adds two numbers""" |
| 3 | + return x + y |
| 4 | + |
| 5 | +def subtract(x, y): |
| 6 | + """This function subtracts two numbers""" |
| 7 | + return x - y |
| 8 | + |
| 9 | +def multiply(x, y): |
| 10 | + """This function multiplies two numbers""" |
| 11 | + return x * y |
| 12 | + |
| 13 | +def divide(x, y): |
| 14 | + """This function divides two numbers""" |
| 15 | + if y == 0: |
| 16 | + return "Error! Division by zero." |
| 17 | + else: |
| 18 | + return x / y |
| 19 | + |
| 20 | +def calculator(): |
| 21 | + """This function takes user input and performs the chosen operation""" |
| 22 | + print("Select operation:") |
| 23 | + print("1. Add") |
| 24 | + print("2. Subtract") |
| 25 | + print("3. Multiply") |
| 26 | + print("4. Divide") |
| 27 | + |
| 28 | + # Take input from the user |
| 29 | + choice = input("Enter choice(1/2/3/4): ") |
| 30 | + |
| 31 | + # Check if the choice is one of the four options |
| 32 | + if choice in ['1', '2', '3', '4']: |
| 33 | + try: |
| 34 | + num1 = float(input("Enter first number: ")) |
| 35 | + num2 = float(input("Enter second number: ")) |
| 36 | + except ValueError: |
| 37 | + print("Invalid input! Please enter numeric values.") |
| 38 | + return |
| 39 | + |
| 40 | + if choice == '1': |
| 41 | + print(f"{num1} + {num2} = {add(num1, num2)}") |
| 42 | + |
| 43 | + elif choice == '2': |
| 44 | + print(f"{num1} - {num2} = {subtract(num1, num2)}") |
| 45 | + |
| 46 | + elif choice == '3': |
| 47 | + print(f"{num1} * {num2} = {multiply(num1, num2)}") |
| 48 | + |
| 49 | + elif choice == '4': |
| 50 | + print(f"{num1} / {num2} = {divide(num1, num2)}") |
| 51 | + else: |
| 52 | + print("Invalid Input") |
| 53 | + |
| 54 | +# Run the calculator function |
| 55 | +if __name__ == "__main__": |
| 56 | + calculator() |
0 commit comments