Easy Tutorial
❮ Python Heap Sort Python Mongodb Update Document ❯

Python Simple Calculator Implementation

Python3 Examples

The following code is used to implement a simple calculator, including basic addition, subtraction, multiplication, and division operations for two numbers:

Example (Python 3.0+)

# Filename : test.py
# author by : www.tutorialpro.org

# Define functions
def add(x, y):
   """Addition"""

   return x + y

def subtract(x, y):
   """Subtraction"""

   return x - y

def multiply(x, y):
   """Multiplication"""

   return x * y

def divide(x, y):
   """Division"""

   return x / y

# User input
print("Choose operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = input("Enter your choice (1/2/3/4):")

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the 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")

Executing the above code produces the following output:

Choose operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice (1/2/3/4): 2
Enter the first number: 5
Enter the second number: 2
5 - 2 = 3

Python3 Examples

❮ Python Heap Sort Python Mongodb Update Document ❯