Python Program to Create a Basic Calculator
In this article, we will write a python program to create a basic calculator using class, objects, and other methods.
To better understand this example, make sure you have knowledge of the following tutorials:-
Python Class and Objects
Python Constructor
Python Functions
1. A Basic Calculator after using Python:
def cal():
x = ('1. Add \n2. Sub \n3. Multiply \n4. Divide')
print(x)
cal()
cal1 = input('Enter your choice: ')
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number: '))
if cal1 == '1':
x1 = num1 + num2
print('Total number: ' + str(x1))
elif cal1 == '2':
x2 = num1 - num2
print('Total number: ' + str(x2))
elif cal1 == '3':
x3 = num1 * num2
print('Total number: ' + str(x3))
elif cal1 == '4':
x4 = num1 / num2
print('Total number: ' + str(x4))
else:
print("Invalid input")
2. A Basic Calculator after using Python Function:
def add(x, y):
return x + y
def sub(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def menu():
opt = '1. Add \n2. Sub \n3. Multiply \n4. Divide'
print(opt)
menu()
choice = int(input('Please select one of the following : '))
num1 = int(input('Enter your First name : '))
num2 = int(input('Enter your Second name : '))
while True:
if choice == 1:
print('Result : ', add(num1, num2))
break
elif choice == 2:
print('Result: ', sub(num1, num2))
break
elif choice == 3:
x3 = num1 * num2
print('Result: ', multiply(num1, num2))
break
elif choice == 4:
print('Result: ', divide(num1, num2))
break
else:
print('Invaild option')
break
print()
3. A Basic Calculator after using Python Class and Objects:
class cal():
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def sub(self):
return self.a - self.b
def multiply(self):
return self.a * self.b
def divide(self):
return self.a / self.b
a = int(input('Enter First number : '))
b = int(input('Enter Second number : '))
obj=cal(a,b)
while True:
def menu():
x = ('1. Add \n2. Sub \n3. Multiply \n4. Divide')
print(x)
menu()
choice = int(input('Please select one of the following : '))
if choice == 1:
print("Result: ",obj.add())
elif choice == 2:
print("Result: ",obj.sub())
elif choice == 3:
print("Result: ",obj.multiply())
elif choice == 4:
print("Result: ",obj.divide())
elif choice == 0:
print('Again try one of the following')
break
else:
print('Invalid option')
break
print()
Tags:
Python
1 comments
The game is awesome
ReplyDeletePlease leave your comments...... Thanks