Q. Python program to make a simple calculator to perform addition, subtraction, multiplication and division.


Here you will find an algorithm and program in Python programming language to make a simple calculator. First let us understand what is calculator?

Explanation : A calculator is used to make mathematical calculations. In this program we will create a simple calculator that can perform an arithmetic operation (+, -, *, /).

Calculator Program Algorithm


START
Step 1 : Initialise the two numbers.
Step 2 : Ask the user to enter an option by giving 4 options.
Step 3 : After getting the option from the user write if conditions for every operation based on the option.
Step 4 : Perform the respective operation.
Step 5 : Print the result.
STOP

Python Program to 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

# Take input from the user 
ch = input("Enter an operator (+, -, *, /): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if ch == '+':
  print(num1,"+",num2,"=", add(num1,num2))
elif ch == '-':
  print(num1,"-",num2,"=", subtract(num1,num2))
elif ch == '*':
  print(num1,"*",num2,"=", multiply(num1,num2))
elif ch == '/':
  print(num1,"/",num2,"=", divide(num1,num2))
else:
  print("Error! operator is not correct")

Output

Enter an operator (+, -, *, /): *
Enter two operands: 8 6
8.0 * 6.0 = 48.0