Learn How to Build a Basic Calculator in Python: Absolute Beginners Tutorial

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.

Note

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:

python
# 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.

code builder click a token to place it

Build the line that reads a number from the user and converts it to a float. The variable should be named num.

your code will appear here...
input( int( num ) float( "Enter a number: " = str(
Why: 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 + 3 returns 8
Notes
Works with both int and float. If either operand is a float, the result is a float.
Example
10 - 4.5 returns 5.5
Notes
Negative results are expressed with a leading minus sign. No special handling needed.
Example
6 * 7 returns 42
Notes
Python uses *, not x. The ** operator is used for exponentiation, not multiplication.
Example
9 / 4 returns 2.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 // 2 returns 3
Notes
Divides and discards any decimal remainder, rounding toward negative infinity. Useful when you need a whole-number quotient.
Example
7 % 3 returns 1
Notes
Returns the remainder after division. Commonly used to check whether a number is even (n % 2 == 0) or to cycle through a range.
spot the bug click the line that contains the bug

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.

1 def multiply(a, b):
2 result = a * b
3 print result
4 return result
The fix: Change 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.

python
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.

Pro Tip

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:

python
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:

python
# 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}")
Watch Out

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.

  1. Define arithmetic functions

    Write add, subtract, multiply, and divide functions. Each should accept two parameters and return a result. Add a zero-check inside divide that returns an error string instead of crashing when the second argument is zero.

  2. Collect user input

    Use float(input(...)) to read two numbers from the user. Use a plain input() call (no conversion) to read the operation symbol the user wants to perform.

  3. Route the operation with if/elif/else

    Compare the operation string against "+", "-", "*", and "/" using if/elif. Call the matching function with both numbers and assign the return value to a result variable. The else branch handles any unrecognized input.

  4. Display the result

    Use print() with an f-string to output the full expression and its result in one readable line, such as 8.0 + 3.0 = 11.0. This confirms to the user exactly what was computed.

Python Learning Summary Points

  1. input() always returns a string. Use float() or int() to convert it before doing arithmetic.
  2. Python's arithmetic operators are +, -, *, /, //, and %. Division with / always produces a float in Python 3.
  3. Functions defined with def and return let you reuse logic without repeating code. Each arithmetic operation benefits from its own function.
  4. Guard clauses — checking for bad input before doing work — prevent errors like ZeroDivisionError from crashing the program.
  5. An if/elif/else chain routes the user's chosen operation to the correct function. The else branch catches anything that does not match.
  6. 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.

check your understanding question 1 of 5

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.