Building a calculator is one of the best first projects in Python. It touches variables, user input, arithmetic operators, functions, and conditional logic — all in one place. By the end of this tutorial, you will have a working command-line calculator and a clear mental model of how these concepts fit together.
A calculator project works well for beginners because the scope is small enough to finish quickly, but the structure forces you to think about how data flows from input to output. You will read two numbers from the user, decide which operation to run, call a function, and print the result. There are no external libraries to install and no special tools required — just Python and a terminal.
What Python Needs to Do Math with User Input
The input() function reads whatever a user types at the command line and returns it as a string. Strings cannot be added, subtracted, multiplied, or divided the way numbers can. Before any arithmetic can happen, you must convert the string to a numeric type using int() for whole numbers or float() for numbers that may include a decimal point.
A calculator that only accepts int() would crash if the user typed 3.5. Using float() handles both whole numbers and decimals, so it is the better choice for most basic calculators.
Here is what happens when you run input() and try to use the result directly:
# What input() actually returns
x = input("Enter a number: ")
print(type(x)) # <class 'str'>
# This would raise a TypeError — cannot add a string to a string as math
# x + 5 -- would fail
# Correct approach: convert first
x = float(input("Enter a number: "))
print(type(x)) # <class 'float'>
Once both values are floats, Python can perform arithmetic on them exactly as you would expect.
Build the line that reads a number from the user and converts it to a float. The variable should be named num.
float() wraps input() to immediately convert the string the user types into a decimal number. The correct order is num = float(input("Enter a number: ")). Using int() would fail if the user types a decimal, and str() would not convert anything at all.
Python's Arithmetic Operators
Python provides a full set of arithmetic operators. For a basic calculator, the four essential ones are addition (+), subtraction (-), multiplication (*), and division (/). Two additional operators are worth knowing: floor division (//) and modulo (%).
- Example
5 + 3returns8- Notes
- Works with both int and float. If either operand is a float, the result is a float.
- Example
10 - 4.5returns5.5- Notes
- Negative results are expressed with a leading minus sign. No special handling needed.
- Example
6 * 7returns42- Notes
- Python uses
*, notx. The**operator is used for exponentiation, not multiplication.
- Example
9 / 4returns2.25- Notes
- Division always returns a float in Python 3, even when the result is a whole number. Dividing by zero raises a
ZeroDivisionError.
- Example
7 // 2returns3- Notes
- Divides and discards any decimal remainder, rounding toward negative infinity. Useful when you need a whole-number quotient.
- Example
7 % 3returns1- Notes
- Returns the remainder after division. Commonly used to check whether a number is even (
n % 2 == 0) or to cycle through a range.
The function below is supposed to multiply two numbers and return the result, but it has one bug. Click the line you think is wrong, then hit check.
print result to print(result). In Python 3, print is a function and requires parentheses around its argument. The syntax print result is valid Python 2 but raises a SyntaxError in Python 3.
Writing the Calculator Functions
Separating each operation into its own function is a habit worth building early. When a calculation lives inside a function, it can be tested independently, named clearly, and reused without copying code. The four functions below each accept two parameters and return a single result.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: division by zero is not allowed."
return a / b
Notice that divide handles the zero case before attempting the operation. This is called a guard clause — it checks for a problematic condition up front and returns an error message instead of letting Python raise an exception that would crash the program.
Every function here uses return to pass the result back to the caller. Without return, the function would compute the answer internally but the calling code would receive None — and None cannot be printed as a number.
Now comes the part that routes the user's choice to the right function. The if/elif/else chain reads the operation string the user typed and calls the matching function:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Choose an operation (+, -, *, /): ")
if operation == "+":
result = add(num1, num2)
elif operation == "-":
result = subtract(num1, num2)
elif operation == "*":
result = multiply(num1, num2)
elif operation == "/":
result = divide(num1, num2)
else:
result = "Error: unrecognized operation."
print(f"{num1} {operation} {num2} = {result}")
The last line uses an f-string, which is a Python string that lets you embed variable values directly inside curly braces. The f before the opening quote activates this feature. The result is clean, readable output like 8.0 + 3.0 = 11.0.
"Programs must be written for people to read, and only incidentally for machines to execute." — Harold Abelson & Gerald Jay Sussman, Structure and Interpretation of Computer Programs
The complete calculator script
Here is the full program assembled into a single file you can run directly from the terminal:
# calculator.py — basic four-function calculator
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: division by zero is not allowed."
return a / b
# --- Main program ---
print("Python Calculator")
print("-----------------")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Choose an operation (+, -, *, /): ")
if operation == "+":
result = add(num1, num2)
elif operation == "-":
result = subtract(num1, num2)
elif operation == "*":
result = multiply(num1, num2)
elif operation == "/":
result = divide(num1, num2)
else:
result = "Error: unrecognized operation."
print(f"\nResult: {num1} {operation} {num2} = {result}")
If the user types a letter instead of a number when the program calls float(input(...)), Python raises a ValueError. Handling that gracefully requires a try/except block, which is the natural next concept to explore after completing this tutorial.
How to Build a Basic Calculator in Python
The steps below trace the complete path from an empty file to a working command-line calculator. Each step builds on the previous one.
-
Define arithmetic functions
Write
add,subtract,multiply, anddividefunctions. Each should accept two parameters and return a result. Add a zero-check insidedividethat returns an error string instead of crashing when the second argument is zero. -
Collect user input
Use
float(input(...))to read two numbers from the user. Use a plaininput()call (no conversion) to read the operation symbol the user wants to perform. -
Route the operation with if/elif/else
Compare the operation string against
"+","-","*", and"/"usingif/elif. Call the matching function with both numbers and assign the return value to aresultvariable. Theelsebranch handles any unrecognized input. -
Display the result
Use
print()with an f-string to output the full expression and its result in one readable line, such as8.0 + 3.0 = 11.0. This confirms to the user exactly what was computed.
Python Learning Summary Points
input()always returns a string. Usefloat()orint()to convert it before doing arithmetic.- Python's arithmetic operators are
+,-,*,/,//, and%. Division with/always produces a float in Python 3. - Functions defined with
defandreturnlet you reuse logic without repeating code. Each arithmetic operation benefits from its own function. - Guard clauses — checking for bad input before doing work — prevent errors like
ZeroDivisionErrorfrom crashing the program. - An
if/elif/elsechain routes the user's chosen operation to the correct function. Theelsebranch catches anything that does not match. - F-strings (
f"...") make it easy to embed variable values inside printed output without manual string concatenation.
From here, a natural extension is wrapping the entire calculator in a while True loop so the user can run multiple calculations without restarting the script. Adding a try/except ValueError block around the float() calls protects against non-numeric input. Both of those additions build directly on the patterns introduced in this tutorial.
Frequently Asked Questions
The input() function always returns a string, regardless of what the user types. To use the value in arithmetic, you must convert it to a number using int() for whole numbers or float() for decimals.
int() converts a value to a whole number with no decimal part, while float() converts it to a decimal number. For a calculator that handles values like 3.5 or 10.25, float() is the safer choice since it also handles whole numbers.
The // operator performs floor division, dividing two numbers and rounding the result down to the nearest whole number. For example, 7 // 2 returns 3, not 3.5.
The % operator is the modulo operator. It returns the remainder after dividing two numbers. For example, 7 % 3 returns 1 because 7 divided by 3 leaves a remainder of 1.
Python raises ZeroDivisionError when a program attempts to divide a number by zero, which is mathematically undefined. A well-written calculator checks whether the divisor is zero before performing division and returns an error message instead of crashing.
A function is a reusable block of code defined with the def keyword. In a calculator, each operation — addition, subtraction, multiplication, and division — gets its own function. This makes the code organized, readable, and easy to expand.
The return statement ends a function and sends a value back to wherever the function was called. Without return, a function performs its work but cannot pass a result back to the rest of the program.
if checks a condition first. elif (short for else if) checks additional conditions if the first was false. else runs when no previous condition was true. Together they let a calculator route the user's chosen operation to the correct function.