In this article, we will learn how to make a calculator program in python.
A Calculator is a device which performs the arithmetic operations like addition, subtraction, multiplication, division etc.
I have made 4 functions for each operation.
Addition - add() function, Subtraction - sub() function, Multiplication - mul() function, Division - div() function.
Firstly, we will choose the operation to be performed. Then we take two numbers from the user.
And then we decide which operation to perform using the if-else statements and lastly, we perform the operation on the numbers using the functions.
Let's see the code for this program.
Code for Calculator program in Python:-
# defining add() function to add the numbers
def add(num1,num2):
return num1 + num2
# defining sub() function to subtract the numbers
def sub(num1,num2):
return num1 - num2
# defining mul() function to multiply the numbers
def mul(num1,num2):
return num1 * num2
# defining div() function to divide the numbers
def div(num1,num2):
return num1 // num2
print("CALCULATOR")
print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division")
choice = int(input("Which operation do you want to perform? "))
# taking and storing first number in num1 variable
num1 = int(input("Enter first number: "))
# taking and storing second number in num2 variable
num2 = int(input("Enter second number: "))
if choice == 1:
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 2:
print(num1,"-",num2,"=", sub(num1,num2))
elif choice == 3:
print(num1,"*",num2,"=", mul(num1,num2))
elif choice == 4:
print(num1,"/",num2,"=", div(num1,num2))
else:
print("Invalid Choice!")
Output:-
CALCULATOR
1. Addition
2. Subtraction
3. Multiplication
4. Division
Which operation do you want to perform? 4
Enter first number: 59
Enter second number: 4
59 / 4 = 14.75
Hence, we have completed the program. You can extend this program furthermore by including some more operations.