Variables and Naming in Python
Learn how Python variables work, the rules and conventions for naming them, how dynamic typing changes the rules you may know from other languages, and the naming mistakes to avoid.
What you'll learn
- ✓What a variable is and how Python assigns values to them
- ✓The rules Python enforces for variable names
- ✓The community conventions that distinguish professional code
- ✓How dynamic typing works and what it means in practice
- ✓The most common naming mistakes new developers make
Prerequisites
- •A working Python install — see Install Python and Run Your First Program
- •Familiarity with Python syntax — see Syntax and Indentation
Almost every useful program needs to store information — a user’s name, a price, a list of items, a flag indicating success. Variables are how Python lets you do that. This post covers how variables work, how to name them well, and the rules Python enforces.
What a variable is
A variable is a name that refers to a value. You create one by writing the name, an = sign, and the value you want it to refer to:
age = 25
name = "Alice"
price = 19.99
is_active = True
After those four lines, Python remembers that age refers to the integer 25, name refers to the string "Alice", and so on. You can now use the names anywhere you would have used the values:
print(name) # Alice
print(age + 5) # 30
print(price * 2) # 39.98
The = sign in Python is assignment, not equality. Read it as “is set to,” not “equals.” The expression on the right is evaluated first, and the result is stored under the name on the left.
Variables can be reassigned
A variable can point to a different value at any time. The new value simply replaces the old one:
score = 10
print(score) # 10
score = 20
print(score) # 20
score = score + 5
print(score) # 25
The last line shows a common pattern: take a variable’s current value, do something to it, and assign the result back to the same name.
Python provides shorthand operators for the most common cases. These two lines do the same thing:
score = score + 5
score += 5
The same idea applies to -=, *=, /=, //=, %=, and **=.
Dynamic typing
In some languages you must declare a variable’s type when you create it (int age = 25). Python does not. The type is inferred from the value, and it can change if you reassign:
value = 10 # value is an int
value = "ten" # value is now a string
value = [1, 2, 3] # value is now a list
This is called dynamic typing. It is convenient but means the type of a variable depends on the most recent assignment. In professional codebases this freedom is usually constrained — using type hints, which we will cover later in the series — but the underlying language still allows it.
You can always inspect the current type with the built-in type() function:
value = 10
print(type(value)) # <class 'int'>
value = "ten"
print(type(value)) # <class 'str'>
Naming rules Python enforces
A few rules are absolute. Break them and Python refuses to run your program.
- Names must start with a letter or underscore (
_). They cannot start with a digit. - The rest can include letters, digits, and underscores. No spaces, no hyphens, no other punctuation.
- Names are case-sensitive.
total,Total, andTOTALare three different variables. - You cannot use Python keywords — words the language reserves for its own use, such as
if,for,def,class,import,return,True,False,None.
Examples:
# Legal
user_name = "Alice"
_total = 100
score2 = 9
COUNT = 50
# Illegal — will raise SyntaxError
2nd_place = "Bob" # starts with a digit
user-name = "Alice" # hyphen not allowed
for = 5 # 'for' is a reserved keyword
If you ever want to see the full list of reserved keywords, run this in the REPL:
import keyword
print(keyword.kwlist)
Naming conventions
Beyond what Python forces, the community has settled on conventions that distinguish well-written code from amateur code. They are described in detail in PEP 8, Python’s official style guide. The essentials:
- Variables and functions:
snake_caseuser_name = "Alice" total_price = 199.99 is_logged_in = True - Constants:
UPPER_SNAKE_CASE. Python has no true constants, so this is a convention meaning “do not change this value.”MAX_RETRIES = 5 PI = 3.14159 - Classes:
PascalCase(we’ll meet these later)class UserAccount: ... - Names beginning with a single underscore signal “internal — don’t touch from outside.” A name beginning with double underscore is reserved for special behaviour inside classes.
Choosing good names matters more than the format. A variable called x saves you a few keystrokes today and costs you minutes of confusion next month. Aim for names that are self-explanatory at the call site:
# Less clear
d = 86400
n = ["Alice", "Bob"]
# Clearer
seconds_per_day = 86400
active_users = ["Alice", "Bob"]
Common short names that are acceptable include loop counters (i, j), coordinate pairs (x, y), and well-understood domain terms (db, url). Outside those, prefer descriptive names.
Try it yourself. Open the REPL and create three variables describing yourself — for example, first_name, birth_year, and is_developer. Then print a sentence built from them, like "Yash was born in 1999 and is a developer." Pay attention to the variable names you chose: would they still make sense a month from now?
Multiple assignment
Python lets you assign several variables at once. There are two useful forms.
Parallel assignment — one value per variable:
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
Same value to multiple variables:
a = b = c = 0
print(a, b, c) # 0 0 0
Parallel assignment is especially handy for swapping values, which in many languages requires a temporary variable:
x, y = 10, 20
x, y = y, x
print(x, y) # 20 10
Common naming mistakes
Three traps catch nearly every beginner at least once.
1. Shadowing built-ins
Python has built-in functions with simple, attractive names: list, str, sum, type, id, input. If you create a variable with one of those names, you lose access to the built-in for the rest of that script:
list = [1, 2, 3]
new_list = list("hello") # TypeError: 'list' object is not callable
Fix: rename your variable (items, values, nums — anything but list).
2. Typos that fail silently in interactive use
Because Python is dynamic, a typo creates a new variable instead of raising an error at parse time. This will run without complaint:
total_price = 100
total_pricee = total_price * 1.18 # typo created a new variable
print(total_pricee) # works, but obscures the bug
Modern editors with the Python extension catch this through linting. Use one.
3. Single-letter names outside small scopes
x = compute_something() followed by 40 lines of code using x is hard to read. Reserve short names for short scopes — typically loop bodies and very small helper functions.
Inspecting variables
Two built-in functions are invaluable when learning:
name = "Alice"
print(type(name)) # <class 'str'> — the type of the value
print(id(name)) # 4358239984 — its memory address
type() confirms what kind of value you are working with. id() confirms whether two variables point to the same underlying object — useful when comparing lists or dictionaries later in the series.
Recap
You now know:
- A variable is a name that refers to a value, created with
= - Variables can be reassigned freely and are dynamically typed
- Names must follow Python’s syntactic rules and should follow PEP 8 conventions (
snake_casefor variables,UPPER_SNAKE_CASEfor constants) - Multiple assignment makes swaps and parallel updates concise
- The three big naming traps: shadowing built-ins, silent typos, and overly short names
Next steps
In the next post we look at Python’s data types — the categories of values you can store in variables, when to use each, and how to check what type you’re working with.
→ Next: Python Data Types: The Complete Beginner Guide
Questions or feedback? Email codeloomdevv@gmail.com.