CREATING BASIC CALCULATOR USING OOPS IN PYTHON - NEPOHITS

Basic calculator using object oriented programming (oops) in python




1.    1.    Create one Class Calculator: (functions using def in python)

2.    While Creating object of calculator class take two user inputs

3.    If and else conditions were used.

4.    Result of Addition, subtraction, multiplication and division of  two inputs.

Let’s try to implement the code:-


# Code by Nawaj Sarif
# create a class calculator

class Calculator:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2
    def add (self):
        return self.num1 + self.num2
    def subtract (self):
        return self.num1 - self.num2
    def multiply (self):
        return self.num1 * self.num2
    def Divide (self):
        return self.num1/self.num2

   
print ("*******Please select the operation:*********\n"\
           " 1. Add\n "\
           " 2. Subtract\n"\
           " 3. Multiply\n"\
           " 4. Divide\n"\
)

select = int(input("***Select the operation******\n"))
# (creating the object)

num1 = float(input("Enter the first number:\n"))
num2 = float (input("Enter the second number:\n"))
my_Result = Calculator(num1,num2)

if select == 1:
       print (num1, "+", num2, "=",my_Result.add())
elif (select == 2):
    print (num1, "-", num2, "=",my_Result.subtract())      
elif (select == 3):
    print (num1, "*", num2, "=",my_Result.multiply())
elif(select ==4):
    print (num1, "/", num2, "=",my_Result.Divide())

else:
  print ("invalid number")




OUTPUT


*******Please select the operation:*********

 1. Add

  2. Subtract

 3. Multiply

 4. Divide

 

***Select the operation******

1

Enter the first number:

45

Enter the second number:

43

45.0 + 43.0 = 88.0


we have used oops program in python to create a Basic calculator.

If You have any queries or suggestion, please feel free to ask! Thank You.








1 comment:

If you have any doubts please let's me know

Powered by Blogger.