Write a program to Make a Simple Calculator in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | # Program make a simple calculator that can add, subtract, multiply and divide using functions # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") # Take input from the user choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) 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") |
This Python program is a simple calculator that can perform four basic arithmetic operations: addition, subtraction, multiplication, and division. The program defines four functions, one for each operation: add(x, y)
, subtract(x, y)
, multiply(x, y)
, and divide(x, y)
. Each function takes two numbers as arguments and returns the result of the corresponding operation.
The main program starts by prompting the user to select an operation from a menu of four options (1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division). It then prompts the user to enter two numbers and assigns them to the variables num1
and num2
.
The program uses an if-elif block to check the value of the variable choice
, which represents the user’s selection. Depending on the value of choice
, the program calls the corresponding function and passes num1
and num2
as arguments. The result is then printed out.
For example, if the user selects option 2 (subtraction), enters the numbers 150
and 50
, the output would be: