Giving a Python value a name lets you use it again. A variable is a name in a namespace that refers to an object.
I’ll show how to assign a value to a name and inspect it with print() and type().
TL;DR: Python Variables
A Python variable is a name bound to an object, and assignment creates or rebinds that name.
- Write score = 12 to bind a name to a value.
- Use print(score) to display it and type(score) to inspect its object’s type.
What Is a Variable in Python?
A variable is a name in a namespace that refers to an object.
count = 3
message = "ready"
Python reports an object’s class with type(). The result for count is int, while the quoted word has type str.
Values can also be floats, lists or dictionaries. Assignment syntax stays the same, but the object’s type determines which operations it supports.
How to Create and Use a Python Variable
Assign a value to a name, then use it in an expression or pass it to print() to display it.
Step 1: Assign a value to a name
Put a name left of = and a value or expression on the right. Python binds the resulting value to that name.
price = 8
quantity = 3
total = price * quantity
total refers to the product of the current values.
Step 2: Print the value and inspect its type
Run this complete example from a file named variables_demo.py with python3 variables_demo.py. It demonstrates printing, type inspection, reassignment, unpacking and an f-string.
score = 12
label = "score"
print(score)
print(type(score).__name__)
score = "twelve"
print(score)
print(type(score).__name__)
left, right = "Python", "variables"
left, right = right, left
print(left, right)
name = "Ada"
print(f"Hello, {name}")
12
int
twelve
str
variables Python
Hello, Ada
Multiple assignment evaluates both right-hand values before binding the targets, so the final pair swaps values.
An f-string inserts an expression inside braces in the string, as f”Hello, {name}” does above.
Step 3: Assign several names deliberately
Python can bind multiple names in one assignment.
first = second = []
first.append("shared")
x, y = 4, 9
Appending through first changes the list that second also names. That can be useful for shared state, though separate assignments are clearer when values should stay independent.
For variable-length unpacking, use a starred target such as head, *rest = values to collect remaining items into a list. Without a matching number of items, unpacking raises ValueError.
Python Variable Rules and Scope
Valid names and scope determine whether Python accepts an assignment and where later code can resolve that name. A name must begin with a letter or underscore, then may contain letters, digits and underscores, capitalization changes the name.
| Case | Example | Result |
|---|---|---|
| Valid identifier | item_count | Letters and underscore are allowed |
| Starts with digit | 2items | SyntaxError |
| Hyphen in name | item-count | Parsed as subtraction, not one name |
| Reserved keyword | for | Cannot be used as an identifier |
| Case differs | count and Count | Distinct names |
Capitalization distinguishes names: count and Count are separate bindings. Keep spelling consistent to avoid an undefined name.
Use snake_case names such as total_price in ordinary Python code. A leading underscore is a convention for a non-public name, not access control.
Avoid names such as list or str that shadow built-ins. Choose identifiers that express their role.
At module level, a name belongs to that module’s global namespace. Python determines a function’s local bindings from assignments throughout its body, which explains a common UnboundLocalError.
language = "Python"
def show_language():
return language
# This function raises UnboundLocalError if called:
# def change_language():
# print(language)
# language = "Python 3"
The read in the commented function occurs before its local binding is made, so calling it raises UnboundLocalError. Use a global declaration only when changing a module-level binding is deliberate. A nonlocal declaration selects a name from an enclosing function.
Function lookup checks local names, enclosing scopes, the module namespace, then built-ins. A local can hide a global with the same spelling. At module level, assignments inside if and for blocks use the module namespace, but the assignment must run before the name is read.
An unassigned name raises NameError, while del removes its binding but leaves the object available through other names.
A variable created in a function is not a class attribute. Class attributes belong to the class namespace and are accessed through the class or an instance.
Use int() or float() to convert a numeric string to a number before arithmetic. The conversion raises ValueError if the string does not contain a suitable number, so validate untrusted input before converting.
What to Check When a Variable Behaves Unexpectedly
When a name does not behave as expected, check its spelling, current binding and scope before changing the code. These checks distinguish a missing name from a value with an unexpected type.
| Symptom | Likely cause | Check |
|---|---|---|
| NameError | The name has no binding in the lookup scopes | Check spelling and whether the assignment ran |
| UnboundLocalError | A function assigns the name locally and reads it before assignment | Pass the value as an argument or move the assignment |
| Unexpected operation result | The name refers to a different type than expected | Inspect type(name) and convert validated input if needed |
| Two names change together | Both names refer to the same mutable object | Create separate objects when independent state is intended |
Conclusion: Names Refer to Objects
Choose descriptive names and keep each value’s scope as small as the task allows.
FAQ
These answers address common Python variable questions.
How do you create a variable in Python?
Assign a value to a name, such as count = 3. Python creates the binding when that assignment runs.
How do you check a variable’s type?
Call type(name), for example type(count). It returns the type of the object the name currently refers to.
Can a Python variable change type?
A name can be rebound to an object of another type, such as assigning a string after an integer. The objects keep their own types.
How do you make a variable global in Python?
Use a global declaration inside a function before referencing or assigning that module-level name. Prefer arguments and return values when they fit the design.

