A variable in Python is a name that refers to a value, and you create it by assigning with the equal sign, as in width = 20. There is no declaration step and no type to write: the first assignment creates the name, and later assignments point it at a new value.
This guide covers how assignment works, what you may call a variable, how types and scope behave, and the errors you are most likely to meet. For the language-neutral idea, see what a variable is in programming.
How to create a variable in Python
The Python tutorial says the equal sign is used to assign a value to a variable. Here is its own example, run as a script with print added:
width = 20
height = 5 * 9
print(width * height)
Example output:
900
Python works out the right-hand side first (5 * 9 is 45) and then binds the name on the left to the result. Nothing is printed by the assignment itself. In the interactive prompt you only see output when you evaluate an expression such as width * height.
A variable is a name, not a box
The language reference puts it this way: names refer to objects, and names are introduced by name binding operations. So width = 20 does not put 20 inside a container called width. It makes the name width refer to an object that holds the value 20.
This matters as soon as two names point at the same object:
first = [1, 2, 3]
second = first
second.append(4)
print(first)
Example output:
[1, 2, 3, 4]
The line second = first copies no list. It gives the same list a second name, so a change made through one name shows up through the other. The data model page says the same thing about e = f = []: it assigns the same object to both names. Two separate [] literals, by contrast, are guaranteed to be two different lists.
To check whether two names refer to the same object, use the is operator, which compares identity. The id() function returns the identity as an integer. In CPython, that integer is the object's memory address.
Changing a variable and using it in its own update
Assigning again rebinds the name. The old value is not modified, the name simply points somewhere else.
score = 0
score = score + 10
score = score + 5
print(score)
Example output:
15
The right side is evaluated using the current value, then the result is bound to score. That is why score = score + 10 is valid code even though it would be nonsense as algebra. The shorthand score += 10 does the same job; see Python operators explained for the full list.
You can also bind several names in one statement:
x, y = 3, 4
a = b = 0
The first line unpacks two values into two names. The second binds both names to the same object, which is harmless for numbers but is the shared-list situation above when the value is mutable.
Variable naming rules in Python
The lexical analysis page lists what a name may contain: uppercase and lowercase letters, the underscore, digits (but not as the first character), and certain non-ASCII characters. Names have no upper length limit, and case is significant, so total and Total are different variables.
| Name | Valid? | Reason |
|---|---|---|
order_total | Yes | Letters and an underscore |
_cache | Yes | May start with an underscore |
item2 | Yes | Digits are fine after the first character |
2nd_item | No | Starts with a digit |
order-total | No | Python reads the hyphen as subtraction |
class | No | Reserved keyword |
The reference lists the hard keywords that cannot be used as ordinary identifiers: False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with and yield. Words such as match and case are soft keywords and still work as variable names outside the statements that use them.
Beyond what is legal, PEP 8 recommends lowercase names with words separated by underscores, and says constants are usually defined at module level in all capital letters with underscores, such as MAX_OVERFLOW. If a good name collides with a keyword, PEP 8 suggests adding a single trailing underscore, giving class_.
Variable types in Python
You never write a type when you create a variable, yet every value has one. The data model says every object has an identity, a type and a value, and that an object's type never changes after creation. The type lives with the object, not with the name, so a name can be rebound to an object of a different type:
x = 5
print(type(x))
x = "five"
print(type(x))
Example output:
<class 'int'>
<class 'str'>
Nothing was converted. The name x was first bound to an integer object and then to a string object. Python still enforces types when you use a value: "five" + 1 raises a TypeError, because a string and an integer do not support addition with each other.
Mutable and immutable values
The data model separates objects whose value can change (mutable) from those whose value cannot (immutable). It gives numbers, strings and tuples as immutable, and dictionaries and lists as mutable. This explains the shared-list example: append changed the list object in place. Strings behave differently, because they cannot be changed in place:
name = "ada"
other = name
name = name.upper()
print(name, other)
Example output:
ADA ada
upper() builds a new string, and the assignment rebinds name to it. other still refers to the original. For immutable values you can treat names as independent; for mutable ones, remember that several names may share one object. See Python tuples explained for an immutable container and Python dictionary examples for a mutable one.
Variable scope: local and global
The execution model says that if a name is bound in a block, it is a local variable of that block, unless declared nonlocal or global. A name bound at module level is a global variable.
greeting = "hello" # global
def shout():
message = greeting.upper() # message is local to shout
return message
print(shout())
print(message)
Example output:
HELLO
Traceback (most recent call last):
File "example.py", line 8, in <module>
print(message)
NameError: name 'message' is not defined
Reading a global from inside a function works. Rebinding it does not, unless you say so with global:
counter = 0
def increment():
global counter
counter = counter + 1
increment()
print(counter)
Example output:
1
The reference says the global statement must precede all uses of the listed names in the block. For a variable in an enclosing function (not module level), use nonlocal instead. Passing values in as parameters and returning results is usually clearer than reaching for either statement.
Common variable errors in Python
NameError: name is not defined
The tutorial shows the error for a variable that was never assigned:
>>> n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
Typical causes are a typo, a different capitalisation, using the name before the line that assigns it, or using it outside the scope where it was bound.
UnboundLocalError
If a name is bound anywhere inside a function, the execution model says all uses of that name in the function refer to the local variable. Reading it before the assignment then fails:
total = 10
def add_one():
print(total)
total = total + 1
add_one()
This raises UnboundLocalError, which the reference describes as a subclass of NameError. The message wording differs between Python versions, so go by the exception name. The fix is either global total at the top of the function, or passing the value in as an argument.
SyntaxError from a bad name
Assigning to a keyword, or starting a name with a digit, is rejected before the program runs. Rename the variable. The table above shows which forms are legal.
Deleting a variable
The del statement unbinds a name:
temp = 42
del temp
print(temp)
The last line raises NameError: name 'temp' is not defined. The execution model counts a del target as a binding operation for scoping purposes, although what it actually does is unbind the name. Rarely needed in everyday code, since names go away on their own when a function returns.
Variables in the interactive prompt
In interactive mode, the last printed expression is assigned to the variable _. The tutorial uses it as a desk calculator:
>>> price = 100.50
>>> tax = 12.5 / 100
>>> price * tax
12.5625
>>> price + _
113.0625
The tutorial says to treat _ as read-only. Assigning to it creates an independent local variable that masks the built-in behaviour. It only exists in the interactive prompt, not in scripts.
Putting variables into text
Once you have values in variables, the usual way to show them inside a sentence is an f-string, covered in Python f-strings. If you are working through the language in order, Python for beginners: core concepts shows where variables fit among the other building blocks.
Frequently asked questions
- Do you have to declare variables in Python?
- No. Python has no declaration keyword. A variable comes into existence the first time you assign a value to its name with =, as in width = 20. Using a name that has never been assigned raises NameError.
- Can a Python variable change type?
- Yes. The type belongs to the object, not to the name, so after x = 5 you can write x = 'five' and the name x now refers to a string. The object itself never changes type once it has been created.
- Does Python have constants?
- Not as an enforced feature. PEP 8 says constants are usually defined at module level and written in all capital letters with underscores, such as MAX_OVERFLOW. That is a convention for readers; Python will still let you reassign the name.
- What is the difference between a local and a global variable?
- A name bound inside a function body is local to that function. A name bound at module level is global. To rebind a module-level name from inside a function, declare it with the global statement first.
- How do I delete a variable in Python?
- Use the del statement, for example del width. The name is unbound, and using it afterwards raises NameError. The value is only freed if nothing else refers to it.
Sources
- Python docs: An Informal Introduction to Python
- Python Language Reference: Execution model (naming and binding)
- Python Language Reference: Lexical analysis (identifiers and keywords)
- Python Language Reference: Data model (objects, values and types)
- PEP 8: Style Guide for Python Code (naming conventions)