Python Keywords & Identifiers
Keywords
Keywords are words the Python interpreter reserves for its own syntax — if, class, for, def, and about 30 others — and using one as a variable name raises a SyntaxError because the interpreter can't tell your intent from its own grammar.
Example: Keywords
# 'class' is a reserved keyword
# class = 5 # SyntaxError: invalid syntax
print("keywords cannot be used as variable names")
Identifiers
An identifier is any name you choose for a variable, function, or class. Picking names that describe what they hold (user_count rather than x) means the code explains itself, cutting down on comments you'd otherwise need to write.
Example: Identifiers
user_count = 42
print(user_count)
Naming Rules
Identifiers must start with a letter or underscore and can only contain letters, digits, and underscores after that — no spaces, hyphens, or symbols like $ or @, which Python reserves for other syntax entirely.
Example: Naming Rules
_valid_name = 1 # starts with an underscore, which is allowed
name2 = 2 # letters followed by a digit, also allowed
print(_valid_name, name2)
Case Sensitivity in Names
Python treats page and Page as two completely separate names, since identifier matching is case-sensitive throughout the language.
A single accidental capitalization mismatch is a common source of NameError bugs that can be confusing to spot by eye.
Example: Case Sensitivity in Names
page = "lowercase" # lowercase variable name
Page = "uppercase" # capitalized name is a completely different variable
print(page)
print(Page)
Best Practices for Names
Favor full, descriptive words over cryptic abbreviations or single letters (except for very short-lived loop counters like i), and follow Python's snake_case convention for variables and functions so your code reads consistently with the rest of the ecosystem.
Example: Best Practices for Names
total_price = 19.99 # descriptive snake_case name for a price value
for i in range(3): # short name "i" is fine for a throwaway loop counter
print(i)
print(total_price)
- Using a keyword as a variable name, such as
class = 5orfor = 3, which raises aSyntaxError. - Starting an identifier with a digit, like
2nd_place = 1, which is invalid; identifiers must start with a letter or underscore. - Forgetting names are case-sensitive, so
Nameandnameare different variables and using the wrong one raisesNameError.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: