Python Keywords and Identifiers


In Python, keywords and identifiers are fundamental elements that play a crucial role in how Python programs are written and executed. Understanding the rules governing keywords and identifiers will help you write clear, effective, and error-free Python code.

This guide explains what keywords and identifiers are, the rules for their usage, and best practices for naming variables and functions.


Table of Contents

  1. What Are Python Keywords?
  2. List of Python Keywords
  3. What Are Python Identifiers?
  4. Rules for Naming Identifiers in Python
  5. Best Practices for Naming Identifiers
  6. Common Mistakes to Avoid

What Are Python Keywords?

In Python, keywords are reserved words that have special meanings and are used to define the syntax and structure of the Python language. These words cannot be used as variable names, function names, or identifiers because they are reserved for specific language features.

For example, if, else, for, while, class, and def are all keywords in Python. Keywords are essential for writing Python programs, as they define control flow, data structures, and other language constructs.

Python keywords are case-sensitive, meaning that True is a keyword, but true is not.


List of Python Keywords

As of Python 3, here is the complete list of keywords:

False      await      else      import     pass
None       break      except    in         raise
True       class      finally   is         return
and        continue   for       lambda     try
as         def        from      nonlocal   while
assert     del        global    not        with
  • Boolean keywords: True, False, None
  • Control flow: if, else, elif, for, while, break, continue, pass, return, raise, try, except, finally
  • Function-related: def, lambda, yield
  • Exception handling: except, finally
  • Other reserved words: import, from, global, nonlocal, assert, del, is, in, and, or, not, with

To check the current list of Python keywords in your version of Python, you can use the keyword module:

import keyword
print(keyword.kwlist)

What Are Python Identifiers?

Identifiers are names used to identify variables, functions, classes, modules, and other objects in Python. Identifiers allow you to give meaningful names to different elements in your program, making your code easier to understand and maintain.

In Python, an identifier is any name that meets the following criteria:

  • It must begin with a letter (a-z, A-Z) or an underscore (_).
  • The rest of the identifier can contain letters, numbers (0-9), or underscores.
  • It cannot be a Python keyword (like class, return, for, etc.).
  • Identifiers are case-sensitive, meaning myVariable and myvariable would be considered two different identifiers.

Rules for Naming Identifiers in Python

Here are the key rules for naming identifiers in Python:

  1. First Character: The first character of an identifier must be a letter (uppercase or lowercase) or an underscore (_). It cannot be a number.

    • Valid: myVar, _temp, X1
    • Invalid: 1var, #temp
  2. Subsequent Characters: After the first character, the identifier can contain letters, digits, and underscores.

    • Valid: my_var, temp123
    • Invalid: my@var, var#1
  3. Cannot Be a Keyword: You cannot use Python keywords as identifiers (e.g., for, while, class, def, etc.).

    • Invalid: def = 5, for = 10
  4. Case Sensitivity: Python identifiers are case-sensitive, meaning that myVar, myvar, and MYVAR are all different identifiers.

    • Valid: var, Var, VAR
  5. Length: Python identifiers can be of any length, but they should be meaningful and concise. Long identifiers can make the code harder to read.

    • Valid: counter, i
  6. Underscores: You can use underscores (_) in identifiers, commonly to indicate private variables or methods in classes.

    • Valid: my_variable, _privateVar, __specialVar

Best Practices for Naming Identifiers

Choosing good, descriptive names for your identifiers is important to make your code easy to read and maintain. Here are some best practices:

  1. Use Descriptive Names: Choose names that describe the purpose or use of the variable, function, or class. Avoid single-letter names (except in short loops or mathematical formulas).

    • Good: customer_age, calculate_total
    • Bad: a, temp
  2. Use Snake Case for Variables and Functions: In Python, it is common practice to use snake_case for variable and function names, where words are separated by underscores.

    • Example: total_cost, get_user_input
  3. Use CamelCase for Classes: By convention, class names in Python should be written in CamelCase (also called PascalCase), where each word starts with a capital letter and no underscores are used.

    • Example: UserProfile, DataProcessor
  4. Use Leading Underscore for Private Variables: To indicate that a variable or method is intended for internal use (private), you can prefix it with a single underscore.

    • Example: _internal_count
  5. Avoid Using Single Leading and Trailing Underscores: Avoid using identifiers like _var_ unless they are reserved for special methods, such as __init__ (the constructor) or __str__ (string representation). These are often called "dunder" methods.

  6. Keep It Readable: The most important aspect of naming identifiers is making your code easy to read and understand. Use spaces or underscores to separate words if necessary.

    • Example: calculate_total_price is more readable than calculateTotalPrice.

Common Mistakes to Avoid

  1. Using Keywords as Identifiers: This is a syntax error and can cause your program to fail.

    • Example: class = "hello" (incorrect)
  2. Confusing Case Sensitivity: Since Python is case-sensitive, make sure you don't confuse myVar and myvar. These will be treated as two separate identifiers.

    • Example: myVar and myvar are different.
  3. Starting Identifiers with Numbers: Identifiers cannot start with a number.

    • Example: 123abc = 5 (incorrect)
  4. Overusing Underscores: While underscores can help make identifiers more readable, too many underscores in a name can be excessive and hard to read.

    • Example: ___temp___ is not necessary unless it's required for special cases.
  5. Short, Meaningless Identifiers: Avoid using single-letter or overly short names unless they are common conventions or are used in specific contexts (e.g., loop variables).

    • Example: x, y, z are fine for mathematical formulas, but not for general-purpose variables.