By WebNest Studio Engineering Team
Python Tutorial
Python Keywords and Identifiers
Every name in a Python program — variables, functions, classes, modules — is an identifier, and some words are reserved by the language itself as keywords. Knowing the rules for valid names, the list of keywords, and the naming conventions the Python community follows makes your code correct and instantly readable to other developers.
Why it matters
Names are most of what you write in a program. The rules for a valid name are simple, but breaking them gives confusing errors, and reusing a built-in name such as list or sum silently breaks code further down. Following the naming conventions also makes your code read like the libraries you use.
Keywords
Keywords have special meaning and cannot be used as names: 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 yield. Python also has soft keywords — match, case, type and _ — that are keywords only in specific contexts, so they can still be used as ordinary names elsewhere. The keyword module lists them all.
Identifier Rules
A valid identifier:
- Starts with a letter (a–z, A–Z, or Unicode letters) or an underscore
_. - Continues with letters, digits or underscores — no spaces, hyphens or symbols like
@ $ %. - Cannot start with a digit (
2nd_placeis invalid). - Cannot be a keyword (
class,for...). - Is case-sensitive:
total,TotalandTOTALare three different names.
Naming Conventions (PEP 8)
Beyond validity, follow PEP 8 so code looks familiar: snake_case for variables, functions and modules; PascalCase for classes; UPPER_SNAKE_CASE for constants; a leading underscore (_internal) for "private" names; and double leading underscores (__secret) trigger name mangling inside classes. Avoid shadowing built-ins such as list, str, id or sum.
Examples
Listing keywords and checking identifiers
import keyword
print("Number of keywords:", len(keyword.kwlist))
print("Soft keywords:", keyword.softkwlist)
print(keyword.iskeyword("for"), keyword.iskeyword("match"))
for name in ["total_marks", "_count", "2nd_place", "first-name", "class", "Café"]:
valid = name.isidentifier() and not keyword.iskeyword(name)
print(f"{name!r:15} valid identifier: {valid}")
Number of keywords: 35
Soft keywords: ['_', 'case', 'match', 'type']
True False
'total_marks' valid identifier: True
'_count' valid identifier: True
'2nd_place' valid identifier: False
'first-name' valid identifier: False
'class' valid identifier: False
'Café' valid identifier: True
Naming conventions in practice
MAX_STUDENTS = 30 # constant
class CourseEnrollment: # class: PascalCase
def __init__(self, course_name):
self.course_name = course_name
self._students = [] # "internal" by convention
def add_student(self, student_name): # method: snake_case
if len(self._students) < MAX_STUDENTS:
self._students.append(student_name)
enrollment = CourseEnrollment("Python")
enrollment.add_student("Asha")
print(enrollment.course_name, enrollment._students)
Python ['Asha']
Case sensitivity and shadowing a built-in
score = 10
Score = 20
print(score, Score)
list = [3, 1, 2] # shadows the built-in list() — avoid this!
try:
print(list("abc"))
except TypeError as error:
print("TypeError:", error)
10 20
TypeError: 'list' object is not callable
Common Mistakes
- Using hyphens in names (first-name), which Python reads as subtraction.
- Naming variables list, dict, str, id or input, which hides the built-in functions.
- Starting names with digits or using keywords such as class or from as variable names.
- Inconsistent naming (camelCase variables in a snake_case codebase).
Exercise
For each name in the list, print the name followed by True if it can be used as a variable name and False if it cannot. A usable name is a valid identifier that is not a keyword.
Expected output: total_price True, 2nd_place False, class False, _hidden True (one per line)
import keyword
names = ["total_price", "2nd_place", "class", "_hidden"]
for name in names:
# TODO: work out whether the name is usable, and print the name and the result
pass
Show hints
name.isidentifier()checks the spelling rules, andkeyword.iskeyword(name)checks whether the word is reserved.- Combine them:
name.isidentifier() and not keyword.iskeyword(name).
Show solution
import keyword
names = ["total_price", "2nd_place", "class", "_hidden"]
for name in names:
usable = name.isidentifier() and not keyword.iskeyword(name)
print(name, usable)
Quick quiz
1. Which of these is a valid variable name?
- A. _count
- B. my-name
- C. 2fast
- D. for
Show answer
A. A name may start with an underscore. It may not start with a digit, contain a hyphen, or be a keyword.
2. Which naming style does PEP 8 recommend for a class?
- A. snake_case
- B. PascalCase
- C. UPPER_CASE
- D. camelCase
Show answer
B. Classes use PascalCase, functions and variables use snake_case, and constants use UPPER_CASE.
3. What is the effect of writing list = [1, 2, 3]?
- A. The name list now refers to your data, so the built-in list() can no longer be called by that name
- B. A syntax error
- C. Nothing unusual
- D. The built-in is renamed
Show answer
A. This is called shadowing a built-in. A later call such as list("abc") fails with TypeError.
Interview questions
What is the difference between a keyword and an identifier?
Show answer
A keyword is a word reserved by the language with a fixed meaning, such as if, for, class and return; it cannot be used as a name. An identifier is a name chosen by the programmer for a variable, function, class or module. It must start with a letter or underscore, continue with letters, digits or underscores, and is case-sensitive.
What do a leading underscore and a double leading underscore mean in a name?
Show answer
A single leading underscore, as in _helper, is a convention meaning "internal, do not rely on this from outside"; Python does not enforce it. A double leading underscore inside a class, as in __balance, triggers name mangling: the attribute is stored as _ClassName__balance, which avoids accidental clashes in subclasses. Names with double underscores on both sides, such as __init__, are special methods defined by the language.
Key Points to Remember
- Python has 35 keywords plus soft keywords (match, case, type, _).
- Identifiers start with a letter or underscore and contain only letters, digits and underscores.
- Identifiers are case-sensitive.
- Follow PEP 8: snake_case, PascalCase for classes, UPPER_CASE for constants.
- Never shadow built-in names.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering