How to create a basic calculator in Python

Let’s write a program that would work as a basic calculator. Our calculator would help us solve basic arithmetic functions like:

  • addition
  • subtraction
  • multiplication
  • division

Code

def add(a,b):
return a + b
def subtract(a,b):
return a - b
# Function to multiply two numbers
def multiply(a,b):
return a * b
# Function to divide two numbers
def divide(a , b):
return a / b
num1 = 1
num2 = 2
print(num1, "+", num2, "=", add(num1, num2))
print(num1, "-", num2, "=", subtract(num1, num2))
print(num1, "*", num2, "=", multiply(num1, num2))
print(num1, "/", num2, "=", divide(num1, num2))

Explanation

We created four different functions:

  1. add(): As the name suggests, this function adds two variables.

  2. subtract(): This function subtracts variable one from variable two.

  3. multiply(): This multiplies the two variables.

  4. divide(): Variable one is divided by the second variable upon calling this function.

Next, we took two variables, num1 and num2. Each variable has been assigned two integers.

Upon printing the functions above, we get the result of adding, subtracting, multiplying, and dividing num1 and num2.

In order to play around with the calculator, you can change the values for num1 and num2.