Once upon a time, my father was after my life to learn tables. Every second-third day I used to get scolded upon this. But one bright day I made a calculator using python myself and presented it to him. After that vivid day, he never asked about tables. Yess!
Hey guys, welcome to Technifyed I’m Vasav Trehan and today I’ll teach you how to create your own Basic Calculator using Python. Surprising isn’t it!
The calculator which we’ll be creating today will be able to perform addition, subtraction, multiplication & division for 2 numbers/digits.
To continue further you will need to know Functions, Variables, Numbers & Conditional statements. Well without waiting even for a second let’s start.
Here we go with the first line of code
def calc(num1, opr, num2):
We know that “def” is the initial word in a function followed by the name in this case “calc” there are 3 variables first num1 second or which is operation and third num2.
if opr == '+':
return num1 + num2
This is a conditional statement & here we tell Python that if the operation is ‘+’ then add the two numbers. You can replace return with print but then you need to put the calculation in between brackets. We do the same for subtraction, multiplication & division like this.
if opr == '-':
return num1 - num2
if opr == '*':
return num1 * num2
if opr == '/':
return num1 / num2
This piece of code is optional to put
else:
print('This calculator performs only the 4 basic operations')
In this piece of code, we’re telling Python says “This calculator performs only the 4 basic operations” if the user inputs an operation or something else that this calculator can’t perform.
This is the code in all-
def calc(num1, opr, num2):
if opr == '+':
return num1 + num2
if opr == '-':
return num1 - num2
if opr == '*':
return num1 * num2
if opr == '/':
return num1 / num2
else:
print('This calculator performs only the 4 basic operations')
Input
calc(3, '+', 6)
Output
9