Write a python program to make a calculator
Answers
Simple Calculator by Making Functions
# Program make a simple calculator
# 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")
while True:
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(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))
break
else:
print("Invalid Input")
The following codes will have to be typed in script mode, saved and then executed.
CODE:
x = int(input("Enter a value:"))
y = int(input("Enter a second value:"))
print("Below are the numbers signifying each operation. Choose what operation you'd like to perform.")
print("Addition - 1", "Subtraction - 2", "Multiplication - 3", "Division - 4", sep="\n")
op = int(input("Enter the operation you'd like to perform:"))
if op == 1:
print("You've chosen addition. The resultant value is", x + y)
elif op == 2:
print("You've chosen subtraction. The resultant value is", x - y)
elif op == 3:
print("You've chosen multiplication. The resultant value is", x*y)
elif op == 4:
print("You've chosen division. The resultant value is", x/y)