Calculator Program in Python

Written by

Himani Kohli

In this python program code, we will learn to form a simple calculator which will perform a basic arithmetic operation such as addition, subtraction, multiplication, and division, depending upon the input given by the user.

Here, we have made a function named calc(n) which will further perform the desired operation.

# Algorithm

  1. Define a function named calc(n).
  2. In the function, sum “s” and product “p” initialize to 0 and 1 respectively.
  3. Take two numbers as input from the user, further operations are performed on it.
  4. For different values of i we will perform different operations and it is passed in the function calc().
  5. We perform the different operation on the number which is input by the user .
  6. Exit.

Code:

def calc(n):

    s=0

    p=1

    a=int(input("first number"))

    b=int(input("second number"))

    if n==1:

        s=a+b

        print("sum",s)

    elif n==2:

        p=a*b

        print("prod",p)

    elif n==3:

        s=a-b

        print("diff",s)

    else:

        p=a/b

        print("divide",p)

i=int(input("enter for calculation 1. add 2. product 3.subtract 4.divide"))

calc(i)

 

Output:

enter for calculation 1. add 2. product 3.subtract 4.divide 2

2

3

prod 6

enter for calculation 1. add 2. product 3.subtract 4.divide 4

first number4

second number2

divided 2.0

Calculator Program in Python