⊕
⊖
Contents
Calculator Program
In this tutorial, we will learn how to write a basic calculator program in Python.
This calculator contains the following four basic arithmetic operations.
- Addition
- Subtraction
- Multiplication
- Division
We use Arithmetic Operators to perform these operations.
Python Program
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid Input")
Output 1
% python3 main.py
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 1
Enter first number: 4
Enter second number: 5
4.0 + 5.0 = 9.0
Output 2
% python3 main.py
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 4
Enter second number: 5
4.0 * 5.0 = 20.0
What does this program do?
- We have four functions: add(), subtract(), multiply(), and divide(), which take two numbers as arguments and perform the corresponding arithmetic operation.
- We print a menu of operation that the calculator can perform which are Add, Subtract, Multiply, Divide.
- Then we prompt the user to enter their choice of operation using input() builtin function.
- Then prompt the user to enter two numbers.
- We use an if-elif-else block to check the value of the choice variable and call the appropriate function. If the user enters an invalid choice, the program prints an error message.
Summary
In this tutorial of Python Examples, we presented an example of a simple calculator. You can add more functionality to it like add other operations. Or you can make it more robust by adding error handling, etc.