In this tutorial, you will learn to write a Python program to make a simple calculator.
You can use this calculator to add, subtract, divide, and multiply two numbers.
To understand this program you should have an understanding of the following topics:
Python Program To Make A Simple Calculator
# Function to add two numbers
def add(x, y):
return x + y
# Function to subtract two numbers
def subtract(x, y):
return x - y
# Function to multiply two numbers
def multiply(x, y):
return x * y
# Function to divide two numbers
def divide(x, y):
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
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter first number: 3
Enter second number: 7
3.0 + 7.0 = 10.0
In this program, we define four functions add(), subtract(), multiply(), and divide().
These functions perform the basic arithmetic operations of addition, subtraction, multiplication, and division.
We then print a menu of choices for the user.
Then we prompt the user to enter their choice and the two numbers to perform the operation on.
We use a series of conditional statements to check the user’s choice and call the appropriate function to perform the operation.
Finally, we print the result of the operation to the console.
When you run this program, you’ll see a simple calculator menu with four options.
You can enter your choice (1/2/3/4).
After entering the right choice, you can enter the two numbers to perform the operation on.
The program will then perform the operation and print the result to the console.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.