Python calculator program using functions

Description: Write a simple calculator in Python using a function. It should support +, -, * and /.

Rules and hints:

  • Write one function that takes two numbers and an operator.
  • Check for division by zero.
  • Return a message for a wrong operator.

Python calculator program

def calculate(a, b, op):
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    else:
        return "Invalid operator"

print(calculate(10, 5, "+"))
print(calculate(10, 5, "-"))
print(calculate(10, 5, "*"))
print(calculate(10, 5, "/"))
print(calculate(10, 0, "/"))

Output:

Tutorials Class - Output Window

15
5
50
2.0
Cannot divide by zero

How it works

  • The function checks the operator with if and elif and returns the answer.
  • A division by zero would crash the program, so we check b == 0 first.
  • You can read the numbers and the operator with input() to make it interactive.

Related: Python Functions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.