Skip to main content

Simple calculator using python




In this tutorials, we are going to create a simple calculator using python. For this ,we ask user to select the operation which are mention below
  • 1 for addition
  • 2 for subtraction
  • 3 for division
  • 4 for multiplication
Again ask the user to insert the number for desired operation

In this program we used function,operators and if else statement.

  • Function in python
Function are those command of code which will only run when it is called.In python function is define by def keyword.


Syntax:
   def addition(x,y):
   return x + y

  • Operators in Python
Operators are used to perform the mathematical operation. In this program we used +,-,/ and * arithmetic operators to perform addition ,subtraction ,division and multiplication respectively.

Syntax:
    x + y
    x - y
    x / y
    x * y
  • if else in python(conditional statement)
Conditional statements are used to perform the unrelated action under the different condition.

Syntax:
   if choice== '1':
  {
  Addition
  }
  elif choice== '2':
  {
   subtraction
  }  

   elif choice== '3':
  {
  division
  }
 elif choice== '4':
 {
  multiplication
 }
 else
 {
  invalid input
 }
 
Code:

def addition(x, y):
   return x + y
def subtract(x, y):
   return x - y
def division(x, y):
   return x / y
def multiplication(x, y):
   return x * y

print("Select operation.")
print("1.Addition")
print("2.Subtract")
print("3.division")
print("4.multiplication")

 
choice = input("Enter choice(1/2/3/4): ")

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

if choice == '1':
   print(a,"+",b,"=", addition(a,b))

elif choice == '2':
   print(a,"-",b,"=", subtract(a,b))

elif choice == '3':
   print(a,"/",b,"=", division(a,b))

elif choice == '4':
   print(a,"*",b,"=", multiplication(a,b))
else:
   print("Invalid input")

Output