Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 46

Calculator Program in Python

In this lesson: Make a simple calculator in Python with functions and if-elif — add, subtract, multiply, divide — code with output.

What we are building

A calculator takes two numbers and an operator (+, -, *, /) and shows the result. It is a great first project that brings together input, conditions, functions and error handling. We will build it step by step and make it safe against divide by zero.

💡 Remember: convert input with float(), or "2" + "3" gives "23" instead of 5.

A basic calculator

a = float(input("First number: "))
op = input("Operator (+ - * /): ")
b = float(input("Second number: "))

if op == "+":
    print(a + b)
elif op == "-":
    print(a - b)
elif op == "*":
    print(a * b)
elif op == "/":
    print(a / b)
else:
    print("Invalid operator")
First number: 10
Operator: +
Second number: 5
15.0

We read two numbers (converted to float) and an operator, then use if-elif to run the matching operation. else catches an invalid operator.

Using functions

Putting each operation in a function keeps the code clean and reusable.

def calculate(a, b, op):
    if op == "+": return a + b
    if op == "-": return a - b
    if op == "*": return a * b
    if op == "/": return a / b
    return "Invalid operator"

print(calculate(20, 4, "/"))
5.0

Now the logic lives in one calculate function you can call anywhere, which is cleaner than repeating if-elif everywhere.

Handling divide by zero

def calculate(a, b, op):
    if op == "/":
        if b == 0:
            return "Cannot divide by zero"
        return a / b
    # ... other operators

print(calculate(10, 0, "/"))
Cannot divide by zero

Dividing by zero would crash the program, so we check if b == 0 first. You could also use a try-except ZeroDivisionError block.

Let the user do many calculations until they choose to quit.

while True:
    a = float(input("First number: "))
    op = input("Operator: ")
    b = float(input("Second number: "))
    print("Result:", calculate(a, b, op))

    again = input("Another? (y/n): ")
    if again != "y":
        break
print("Goodbye")

The while True loop repeats the calculator. After each result we ask if the user wants another; typing anything other than "y" breaks out and ends.

Common mistakes

  • Not converting input. input() gives a string — use float() or int() for maths.
  • Ignoring divide by zero. Always guard the division with a check or try-except.
  • No else for bad operators. Handle invalid input so the program does not fail silently.
  • Comparing with =. Use == to compare the operator, not the assignment =.

Summary

  • A calculator reads two numbers and an operator, then computes.
  • Convert input with float() before doing maths.
  • Use if-elif or a calculate function to pick the operation.
  • Guard against divide by zero with a check or try-except.
  • Add a while loop to let the user repeat.

Next, learn decisions in if-else in Python, or reuse code with Python functions.

Frequently Asked Questions

How do I take number input in Python?
Use input() to read text, then convert it with float() or int() — for example a = float(input("Enter a number: ")). Without converting, the input stays as a string and maths will not work.
How do I handle divide by zero in Python?
Check if the divisor is zero before dividing, or wrap the division in a try-except for ZeroDivisionError. Show a message like "cannot divide by zero" instead of letting the program crash.
Should I use if-elif or functions for a calculator?
Both work. if-elif is fine for a first version. Putting each operation in a function makes the code cleaner and reusable, and is a good habit as programs grow.
How do I make the calculator repeat?
Wrap it in a while True loop and offer an option to quit. After each calculation, ask if the user wants another, and break out of the loop when they choose to exit.
Why does my calculator join numbers instead of adding?
That happens when the inputs are still strings — "2" + "3" gives "23". Convert inputs to float or int first so Python does real arithmetic.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 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.
Next topicReverse String or List Your progress: 46 / 66 (70%) · Lesson 47 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free