📘 Lesson · Lesson 78
Calculator Program
Calculator Program in Python
A simple calculator that performs the four basic operations based on the user's choice.
Python Program
Python
def calculator(a, b, op):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return a / b if b != 0 else "Cannot divide by zero"
return "Invalid operator"
print(calculator(10, 5, "+")) # 15
print(calculator(10, 5, "*")) # 50
print(calculator(10, 0, "/"))Expected Output
15
50
Cannot divide by zero
How it Works
- The function checks the operator and returns the result.
- Division guards against divide-by-zero.
Summary
- A simple calculator that performs the four basic operations based on the user's choice.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.