Python Program - Make a Simple Calculator
www.igiftmoc.aedi
here's a Python program that makes a simple calculator:
# function to add two numbers def add(x, y): return x + y # function to subtract two numbers def subtract(x, y): return x - y # function to multiply two numbers def multiply(x, y): return x * y # function to divide two numbers def divide(x, y): return x / y # get input from user print("Select operation.") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter choice (1/2/3/4): ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) # perform selected operation if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) else: print("Invalid input")
In this program, we define four functions to perform the basic arithmetic operations: add()
, subtract()
, multiply()
, and divide()
. Each function takes two numbers as input and returns the result of the corresponding operation.
We then get input from the user to select an operation and enter two numbers. We use the input()
function to get the user's choice of operation and store it in the choice
variable. We also use the float()
function to convert the user's input of numbers from string to float.
Finally, we use an if
statement to perform the selected operation and print out the result using the corresponding function. If the user enters an invalid choice, we print out an error message.