How to create calculator in Python using functions

Pybeginner
By -
0



Here, we will create a Calculator in Python using functions. 

This will be a good exercise to practice functions in python and also to start making things a little complex.

As always, open your text editor and create a new Python file.

The calculator we are going to create will perform only 4 operations, which will be addition, subtraction, multiplication and division.

 

# function for adding
def addition(a, b):
return a + b

#function for subtraction
def subtraction(a, b):
return a - b

#function for multiplication
def multiplication(a, b):
return a * b

#function for division
def division(a, b):
return a / b

#Menu
print("Enter:\n\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n")

choice = input("Enter choice: ")

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

if choice == '1':
print(addition(a,b))

elif choice == '2':
print(subtraction(a,b))

elif choice == '3':
print(multiplication(a,b))

elif choice == '4':
print(division(a,b))

else:
print("Invalid choice")

 

Output:

 

Enter:

1.Addition
2.Subtraction
3.Multiplication
4.Division

Enter choice: 3
Enter the first number: 2
Enter the second number: 3

6

 

Post a Comment

0Comments

Post a Comment (0)