Let’s write a program that would work as a basic calculator. Our calculator would help us solve basic arithmetic functions like:
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))
We created four different functions:
add(): As the name suggests, this function adds two variables.
subtract(): This function subtracts variable one from variable two.
multiply(): This multiplies the two variables.
divide(): Variable one is divided by the second variable upon calling this function.
Next, we took two variables,
num2. Each variable has been assigned two integers.
Upon printing the functions above, we get the result of adding, subtracting, multiplying, and dividing
In order to play around with the calculator, you can change the values for
View all Courses