Python · Beginner

Variables in Python

7 min readUpdated September 24, 2026Every example verified

In short: A Python variable is a name bound to a value by an assignment such as count = 3. It exists from that first assignment, needs no type declaration, and can later be rebound to a value of any type. The name is a label attached to the value, not a box holding it.

What a variable is

A variable gives a value a name so you can refer to it later. Writing count = 3 does two things: it creates an integer object with the value 3, and it binds the name count to that object. From then on, wherever count appears in an expression, Python looks up the binding and uses the object.

Python has no declaration step: no keyword such as var or int in front of the name, and no need to say what type it will hold. The name does not exist until the first assignment runs, and reading it before that raises NameError. Because the binding is all there is, you can later assign a string to a name that used to hold a number; Python allows it, although keeping one meaning per name makes programs far easier to follow.

The most useful mental model is a label, not a box. In a box model, b = a would copy the contents of a into a second box; in Python it attaches a second label to the same object. For numbers and strings, which cannot be changed in place, the distinction never shows. For lists and other changeable objects it matters at once: a change made through one name is visible through the other, because there is only one object, as the third example shows.

Naming rules and conventions

A name may contain letters, digits and underscores, must not start with a digit, and must not be a keyword such as if, for, class or None. Names are case sensitive, so rate and Rate are two different variables. The convention across the Python community, written down in the PEP 8 style guide, is snake_case for variables: lower-case words joined by underscores, such as unit_price. Names in ALL_CAPS are reserved by convention for values the program never reassigns, such as MAX_RETRIES.

Choose names that say what the value means: seconds_left beats s, and is_open beats flag. The extra keystrokes are repaid every time someone, including you next month, reads the code.

Syntax

 Python · syntax
name = value              # bind a name to a value
a, b = 1, 2               # bind several names at once
a, b = b, a               # swap: the right side is evaluated first
x = y = 0                 # both names bound to the same object
count += 1                # shorthand for count = count + 1

The right-hand side is evaluated completely before any name on the left is bound. That is why the swap works without a temporary variable.

Assigning, reading and updating

A car park counter goes up and down; a second variable is computed from it.

 Python
cars = 12
print("Cars parked:", cars)
cars = cars + 5
print("After arrivals:", cars)
cars -= 3
print("After departures:", cars)
spaces_free = 40 - cars
print("Free spaces:", spaces_free)

Output

Cars parked: 12
After arrivals: 17
After departures: 14
Free spaces: 26

cars = cars + 5 reads the current value (12), computes 17 and rebinds cars to the new integer; the old 12 is simply no longer referenced. cars -= 3 is the same operation in shorter form. spaces_free is created by its first assignment, from an expression that uses cars at that moment; changing cars later would not update it.

Several names at once, and swapping

Two shelf labels change places without a temporary variable.

 Python
left, right = "jam", "honey"
print(left, right)
left, right = right, left
print(left, right)
width = height = 10
height = 25
print(width, height)

Output

jam honey
honey jam
10 25

The first line binds two names from two values in one statement. In the swap, Python evaluates the right side right, left first, producing ("honey", "jam"), and only then binds the names, so nothing is overwritten too early. width = height = 10 binds both names to the same 10; reassigning height moves that one label only, which is why width still prints 10.

A variable is a label, not a box

Two names for one list, then two names for one number.

 Python
order = ["tea", "scone"]
same_order = order
same_order.append("jam")
print(order)
print(order is same_order)
total = 5
other = total
other = other + 1
print(total, other)

Output

['tea', 'scone', 'jam']
True
5 6

same_order = order does not copy the list; it adds a second name for the one list object, and is confirms that. Appending through either name changes the shared list. The integer case looks different only because other + 1 builds a new integer and rebinds other to it, while total keeps its label on the untouched 5. The lists lesson shows how to make a real copy.

Common mistakes

  • Reading a variable before it has been assigned

    Why it goes wrong: A name only exists once assigned, so print(total) before total = 0 raises NameError. The common version is updating a counter inside a loop without setting it to 0 first.

    Fix: Give the variable a starting value before the first line that reads it.

     Python · fix
    total = 0
    for n in [4, 5, 6]:
        total += n
    print(total)
  • Using == where = was meant, or the other way round

    Why it goes wrong: = assigns; == compares. count == 0 on a line by itself evaluates to True or False and throws the result away, leaving count unchanged, while if count = 0: is a SyntaxError.

    Fix: Assign with a single =; compare with == inside conditions.

  • Shadowing a built-in name

    Why it goes wrong: list = [1, 2] or sum = 0 rebinds the built-in name for the rest of the program; a later call such as list("abc") fails with TypeError: 'list' object is not callable.

    Fix: Pick a descriptive name instead, such as items or running_total; most editors highlight built-in names so the clash stands out.

  • Assuming b = a makes an independent copy

    Why it goes wrong: For mutable objects such as lists, both names refer to one object, so changes through b show up in a.

    Fix: Copy explicitly when you need independence, for example b = a.copy() or b = list(a).

     Python · fix
    a = [1, 2]
    b = a.copy()
    b.append(3)
    print(a, b)  # [1, 2] [1, 2, 3]

Valid and invalid names

NameAllowed?Reason
unit_priceyesletters and an underscore, starts with a letter
_cacheyesa name may start with an underscore
row2yesdigits are fine after the first character
2rownocannot start with a digit
unit-pricenoa hyphen is the subtraction operator
classnoa keyword
MaxSizeyeslegal, but PEP 8 expects max_size for a variable

Where you use this

Any program that reads input is a small exercise in variables: read a line into a name, convert it, compute from it, print. Suppose a stall sells tickets at a fixed price and the operator types how many were sold. The price never changes while the program runs, so it gets an upper-case name; the count and the total are ordinary variables. Naming each value makes the calculation readable and lets you change the price in one place instead of hunting for a literal 12 through the code.

 Python · in practice
TICKET_PRICE = 12
sold = int(input())
takings = sold * TICKET_PRICE
print("Takings:", takings)

Key points

  • Assignment name = value creates the variable; there is no declaration.
  • A name can be rebound to a value of any type, but keep one meaning per name.
  • Names may contain letters, digits and underscores, cannot start with a digit, and are case sensitive.
  • Use snake_case for variables and ALL_CAPS for values you never reassign.
  • b = a makes two labels for one object; it copies nothing.
  • a, b = b, a swaps because the right side is evaluated before any binding.

Try it yourself

The program computes a bill from a quantity written into the code. Change it so the quantity is read from input with int(input()) instead, keeping the output format the same.

Your program
price = 40
quantity = 3
print("Total:", price * quantity)
Input the program receives: 5
Expected output: Total: 200

Practise this

Exercises for this lesson are in the Python practice set.

Open the Python playground

Frequently asked questions

Does a Python variable have a type?

The variable itself does not; the object it refers to does. x = 5 binds x to an int object, and x = "five" later rebinds it to a str object. type(x) reports the type of whatever x currently refers to. This is what people mean when they call Python dynamically typed.

What is the difference between a variable and a constant in Python?

Python has no constant keyword. A name written in ALL_CAPS, such as MAX_RETRIES = 3, is a promise by the author not to reassign it; the interpreter does not enforce that promise. Type checkers can flag reassignment if you annotate the name with typing.Final, but at run time it is an ordinary variable.

Progress is stored only in this browser.

How this page was checked. Every program on it was run with CPython 3.11 at build time; runs in your browser on CPython 3.14 (Pyodide) by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.