🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeCalculator Program in Python

To turn basic arithmetic into a Python program, use two numbers and an operator. A command-line calculator reads those inputs and uses the operator to choose a calculation.
In this article, I’ll show how to read the inputs and handle division by zero.
TL;DR
A calculator program in Python reads two numbers and an operator, then uses conditional logic to return one arithmetic result.
- Use float() when the inputs may include decimal values.
- Check for a zero divisor and an unsupported operator before showing a result.
- Run the saved file with python3 calculator_demo.py.
What Is a Calculator Program in Python?
A command-line calculator uses a function that receives two values and an operator, then returns a calculated value for display.
The four supported symbols select these operations:
- + adds the two values.
- – subtracts the second value from the first.
- * multiplies the values.
- / divides the first value by the second.
For more examples, see AskPython’s Python operators reference.
How to Build a Calculator Program in Python Step by Step
Save the following program as calculator_demo.py, then run it in a terminal with Python 3.
Step 1: Read the numbers and operator
Ask for the first value, the operator and the second value in that order. Keep the operator as text because it is compared with symbols rather than used in arithmetic.
def calculate(first, operator, second):
if operator == "+":
return first + second
if operator == "-":
return first - second
if operator == "*":
return first * second
if operator == "/":
if second == 0:
raise ZeroDivisionError("division by zero")
return first / second
raise ValueError("unsupported operator")
def main():
first = float(input("First number: "))
operator = input("Operator (+, -, *, /): ").strip()
second = float(input("Second number: "))
try:
result = calculate(first, operator, second)
except ZeroDivisionError:
print("Cannot divide by zero.")
return
except ValueError:
print("Choose +, -, *, or /.")
return
print(f"Result: {result:g}")
if __name__ == "__main__":
main()
The calculate() function returns a value rather than printing it. The main() function owns the prompts and messages, so each part has a clear role.
Step 2: Run one decimal calculation
Run the saved file and enter a decimal, a division symbol and a second number. I ran the same command with 12.5 divided by 2 and got 6.25.
First number: Operator (+, -, *, /): Second number: Result: 6.25

The output shows that decimal input works and that the g format specifier displays this result without a trailing zero.
Step 3: Follow the selected branch
The function’s final ValueError distinguishes an unsupported symbol from a valid operation. main() catches that case and prints the accepted choices.
To add an operation, create a branch for its symbol and update the prompt. Avoid eval() here because the calculator needs only the supported arithmetic symbols.
Common Errors: Invalid Input and Division by Zero
Input can fail during conversion or calculation. The table matches each case to the response this example needs.
| Input | What happens | Response |
|---|---|---|
| Operator ? | No branch matches | Print the supported symbols |
| Number abc | float() raises ValueError | Catch it around conversion and ask again |
| Divide by 0 | Division raises ZeroDivisionError | Check the divisor and show a message |
| Decimal such as 0.1 | Float stores a binary approximation | Use Decimal for exact decimal arithmetic |
I also ran the program with 12.5 divided by zero. It printed “Cannot divide by zero.” and exited with code 0.
Test second == 0 inside the division branch rather than using if not second, since zero is valid for the other operations.
This program accepts one operator between two values. It does not parse a whole expression such as 2 + 3 * 4, so it does not need to decide which operation has precedence. A full expression calculator needs a parser or a carefully restricted expression grammar.
Negative values work as operands because float() accepts a leading minus sign. For example, enter -3 at the first-number prompt, then choose + and enter 5. That is different from the operator prompt, where a minus sign means subtraction between the two entered values.
To add exponentiation, Python uses the double-asterisk operator. The caret symbol has a different meaning in Python, so adding it as a power choice would produce a result the reader may not expect. Keep the menu wording aligned with the operator’s actual behavior.
The current program reports a bad operator after it has read both numbers. Validate the symbol before asking for operands if you want to reject it sooner.
Non-numeric text fails before calculate() runs: float(“abc”) raises ValueError during conversion, outside the handler around the function call. Catch that conversion error separately if the user should be able to try again. Read AskPython’s user input guide for input() behavior and Python’s exception tutorial for handling errors.
Python’s // operator performs floor division and rounds down, while / preserves the fractional result. For example, 7 // 2 returns 3 but 7 / 2 returns 3.5, so use / for this calculator.
A float stores some decimal fractions as nearby binary values, which matters when exact decimal totals are required. Python’s decimal module supports that use case, as the floating-point documentation explains.
Conclusion
A useful extension is a loop with a quit choice, which lets the same function handle another calculation without restarting the file.
Continue with the official Python tutorial on using Python as a calculator, or explore the separate AskPython tutorial for a Tkinter GUI calculator.
FAQ
These answers cover common choices when adapting the small program.
Why use float() instead of int() in a calculator?
float() accepts decimal input such as 2.5 as well as whole-number input. Use int() only when the calculator should reject fractional values.
How can the calculator perform more than one calculation?
Put the prompts and calculation inside a while loop, then provide an exit choice so the user can stop the loop.
Why does division by zero cause an error?
Division by zero raises ZeroDivisionError in Python. Check that the second number is not zero before dividing and print a clear message otherwise.


