Course topics

By WebNest Studio

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.

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_place is invalid).
  • Cannot be a keyword (class, for...).
  • Is case-sensitive: total, Total and TOTAL are 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

Python
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}")
Output
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

Python
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)
Output
Python ['Asha']

Case sensitivity and shadowing a built-in

Python
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)
Output
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).

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 the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.