Python Program to Make a Simple Calculator
A calculator is an electronic device or tool that is used to perform mathematical calculations. Calculators can be simple, such as a basic four-function calculator that can perform addition, subtraction, multiplication, and division, or they can be more advanced, with features such as scientific functions, graphing capabilities, and programming functions. But in this tutorial we are going to create a simple calculator.
Python Code :
The below Python implements a simple calculator:
# define functions for the operations
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
# take input from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# display the menu and get the choice
print("Choose an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
# perform the selected operation and display the result
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 choice")
In this program, we first define four functions for the four basic arithmetic operations: addition, subtraction, multiplication, and division.
We then take input from the user for two numbers using the input() function, and display a menu of operations using the print() function. We get the user’s choice of operation using the input() function.
We then use a series of if-elif statements to perform the selected operation and display the result using the appropriate function.
Finally, we use an else statement to handle an invalid choice. The output will be in the format of “(num1) (operator) (num2) = (result)”.
For example :
Enter first number: 10
Enter second number: 5
Choose an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
10.0 + 5.0 = 15.0
Enter first number: 10
Enter second number: 5
Choose an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 2
10.0 - 5.0 = 5.0
Enter first number: 10
Enter second number: 5
Choose an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 3
10.0 * 5.0 = 50.0
Enter first number: 10
Enter second number: 5
Choose an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 4
10.0 / 5.0 = 2.0