Table of Contents

In Python, keywords are reserved words that have a specific meaning in the language — like if, else, def, or while. You cannot use them as variable names, function names, or identifiers. Identifiers, on the other hand, are the names you assign to variables, functions, classes, and so on. They must follow specific rules: start with a letter or underscore, contain only alphanumeric characters and underscores, and cannot be the same as a keyword. Understanding the difference between keywords and identifiers is essential for writing valid and readable code.

This section will help you develop the habit of using clear and legal names in your code — a critical part of writing Pythonic and bug-free programs.

What you should know before starting:

Beginner Level Practice – Keywords and Identifiers in Python

At the beginner level, it’s important to develop an understanding of what names are allowed in Python and why. You’ll work with valid and invalid identifiers, and explore the restrictions imposed by Python’s keywords. These tasks will help you build the habit of using clear, legal, and descriptive names from the very beginning. This ensures that your code not only works but also reads well — and avoids common beginner errors like using invalid names or shadowing built-in functions.

Task 1: Is This a Valid Identifier?

You are given a list of possible variable names. Your task is to go through each one and decide whether it’s a valid identifier in Python. If not, write a comment explaining why. You can use Python’s built-in isidentifier() method to help you check.


    names = ["1name", "user_name", "for", "emailAddress", "_temp", "first-name"]
    for name in names:
        print(name, "-", name.isidentifier())
  
What this Task Teaches

This task helps you distinguish between valid and invalid identifiers. You’ll learn how to detect naming problems before they cause syntax errors and understand why certain names are not allowed in Python.

Hints and Tips
  • Use name.isidentifier() to programmatically check if a name is valid.
  • Remember: names can’t start with a number or contain special characters like hyphens.
  • Keywords like for are not allowed as identifiers.
Common Mistakes
  1. Using numbers at the start of names: Identifiers can’t begin with a digit — 1name is invalid.
  2. Including hyphens: Use underscores instead — first-name will cause a syntax error.
  3. Using Python keywords: Names like for, if, or def cannot be reused for variables.
  4. Assuming built-in functions are okay to overwrite: Avoid using names like list or str even though they're technically valid.
  5. Forgetting case sensitivity: Name and name are different variables.
Step-by-Step Thinking

You’re validating names. Focus on the rules Python enforces for identifiers.

  1. Iterate over the list of names
  2. Use isidentifier() to check each one
  3. Print the name and whether it’s valid
  4. Optionally, write a comment for each invalid name to explain why
  5. Try adding your own examples after the list
How to Make it Harder
  • Write a function that checks if a name is a Python keyword using the keyword module.
  • Build a script that filters only valid identifiers from a given list.
  • Let the user input names and check them interactively.

Task 2: Rename the Invalid Variables

You are given several invalid variable names. Your task is to rewrite them as valid identifiers by applying the proper rules. Then, write a short comment next to each one explaining what change you made and why.


    # 1value = 10
    # class = "Physics"
    # student-age = 21
    # def = "create"
    # full name = "Alice Smith"
  
What this Task Teaches

This task helps you learn how to fix naming issues and follow Python’s identifier rules. You’ll practice transforming invalid names into valid, readable ones and explain the corrections clearly.

Hints and Tips
  • Replace spaces and hyphens with underscores.
  • Don’t use keywords — change them to something descriptive like class_name.
  • Start names with a letter or underscore, not a digit.
Common Mistakes
  1. Keeping keyword names unchanged: Variables like class or def must be renamed completely.
  2. Adding numbers without context: Instead of value1, prefer initial_value or something meaningful.
  3. Leaving spaces or dashes: Identifiers must use only underscores — no spaces or punctuation.
  4. Using vague names: While fixing names, make sure they still reflect their purpose.
  5. Not commenting your fixes: A good developer explains changes — even renaming a variable.
Step-by-Step Thinking

You’re turning invalid names into clean, functional identifiers. Focus on each rule in isolation.

  1. Look for issues: keyword usage, numbers at the start, symbols, or spaces
  2. Replace illegal parts with legal ones (e.g., hyphens → underscores)
  3. Rename keywords to something descriptive (e.g., class → class_name)
  4. Write a comment beside each fix to explain your change
  5. Test your new variables in a simple program to confirm they work
How to Make it Harder
  • Create a script that automatically converts invalid identifiers into valid ones.
  • Test each fixed name with isidentifier() and keyword.iskeyword().
  • Write your own naming convention guide as a comment block at the top of the file.

Intermediate Level Practice – Keywords and Identifiers in Python

At the intermediate level, it's not enough to just recognize valid identifiers and avoid keywords — you must also learn to choose semantic, readable, and maintainable names. Naming conventions matter a lot in real-world development: variable names should describe their purpose, avoid ambiguity, and follow community standards like snake_case. You’ll also begin working with dynamic code (like dictionaries or user-defined functions), where meaningful identifiers and awareness of naming collisions become even more critical.

These tasks will help you become intentional with your naming strategy and give you tools to prevent subtle bugs caused by shadowing built-ins or misusing reserved words.

Task 1: Spot the Naming Issues in This Program

Review the following program. It works, but several of the variable names are poorly chosen or problematic. Your task is to rewrite the code with better identifier names and fix any issues related to reserved keywords or confusing naming.


    def sum(list):
        result = 0
        for item in list:
            result += item
        return result

    print(sum([1, 2, 3, 4]))
  
What this Task Teaches

You’ll learn how to avoid shadowing built-in functions, use meaningful names for functions and variables, and improve the overall clarity of your code. These naming skills greatly affect code readability and future maintenance.

Hints and Tips
  • Never name a variable or function the same as a built-in like list or sum.
  • Use descriptive names like numbers or total instead.
  • Think about what each identifier represents and name it accordingly.
Common Mistakes
  1. Shadowing built-ins: Redefining sum means you lose access to Python’s original sum() function — a common and serious mistake.
  2. Generic names like “list”: While valid, they confuse readers and overlap with core concepts.
  3. Reusing vague names in different contexts: A name like result is fine, but it should be more specific if multiple results exist.
  4. Not updating all usages after renaming: If you change list to numbers, make sure it’s changed everywhere.
  5. Ignoring naming conventions: Use lowercase_with_underscores for variable and function names.
Step-by-Step Thinking

Think like a code reviewer — your job is to make the code clear and unambiguous without changing its behavior.

  1. Identify names that match Python built-ins or keywords
  2. Rename the function from sum to something like calculate_sum
  3. Rename list to numbers or values
  4. Make sure the internal variable result clearly describes the output
  5. Test the program to ensure it still works with new names
How to Make it Harder
  • Add type annotations to your function and parameters.
  • Write a docstring describing the new function.
  • Expand the function to skip non-numeric elements using isinstance().

Task 2: Classify Identifiers from User Input

Write a program that asks the user to enter a name. Your program should then check and print whether the name is a valid Python identifier and whether it is a Python keyword. Use the isidentifier() method and the keyword module to perform the checks.

What this Task Teaches

You’ll learn how to dynamically test identifiers at runtime, understand the difference between reserved keywords and valid names, and practice basic user input validation. These skills are useful when building compilers, linters, or dynamic code tools.

Hints and Tips
  • Use the input() function to get a name from the user.
  • Use the isidentifier() method to check if it’s valid.
  • Import the keyword module and use keyword.iskeyword() to check if it's a keyword.
Common Mistakes
  1. Forgetting to import the keyword module: The iskeyword() method won’t work without it.
  2. Confusing keywords and invalid identifiers: A keyword like if is a valid identifier by syntax, but still unusable as a name.
  3. Incorrect string formatting: Use f-strings for clearer output messages (e.g., f"{name} is a keyword").
  4. Not checking case sensitivity: If and if are different — only the lowercase one is a keyword.
  5. Skipping edge cases: Test inputs like "", 123, __init__, and None.
Step-by-Step Thinking

This program acts as a mini validation tool. You need to process user input and classify it with clear feedback.

  1. Ask the user to input a string
  2. Check if it’s a valid identifier using isidentifier()
  3. Import the keyword module
  4. Check if the input is a keyword using iskeyword()
  5. Print the result with proper formatting
How to Make it Harder
  • Allow the user to input multiple names (e.g., comma-separated list).
  • Write the results to a CSV file with two columns: name and classification.
  • Convert the script into a reusable function and test it with unit tests.

Advanced Level Practice – Keywords and Identifiers in Python

At the advanced level, you’ll encounter real-world challenges such as naming conflicts, shadowing built-in functions, and designing readable code across multiple files. In large-scale projects, identifiers carry meaning far beyond a single function — they reflect architecture, domain logic, and development standards. Understanding when and why a name might cause problems (even if it's syntactically correct) is crucial. These tasks will train you to write clean, scalable, and safe Python code, while avoiding subtle bugs related to naming.

You’ll also work with tools like the keyword module and reflect on naming conventions in modules and class design.

Task 1: Detect Naming Conflicts in a Real Module

You are maintaining a legacy Python file that defines many variables and functions. Some of them conflict with built-in names or keywords. Your task is to review the given code and refactor all problematic identifiers while keeping the logic unchanged. Make sure to explain each change in a comment.


      # Original problematic code
      def max(values):
          sum = 0
          for val in values:
              sum += val
          return sum

      class = "Beginner"
      input = "data.txt"
  
What this Task Teaches

This task helps you identify dangerous naming patterns, especially when shadowing Python built-ins or using reserved keywords. You’ll learn how to refactor identifiers in a way that improves clarity and prevents subtle runtime issues.

Hints and Tips
  • Use names like total instead of sum.
  • Avoid naming anything input, max, or class.
  • Add comments explaining each change for future developers.
Common Mistakes
  1. Keeping function names like max: This disables use of the original max() function elsewhere in your code.
  2. Using reserved words: Names like class are illegal and will crash your program.
  3. Renaming without consistency: If you rename sum to total, update it everywhere.
  4. Forgetting to test after refactoring: Even a small typo can break logic after renaming variables.
  5. Skipping comments: Always document why changes were made, especially in collaborative projects.
Step-by-Step Thinking

You’re auditing the code like a senior developer. Focus on risk reduction and clarity.

  1. Scan for any names that match built-in functions or keywords
  2. Refactor each one with meaningful, safe alternatives (e.g., max → get_max_value)
  3. Add a comment next to each change explaining the reason
  4. Check that the logic still runs correctly with updated names
  5. Document any naming convention you used for future code style alignment
How to Make it Harder
  • Write a script that parses Python files and flags any identifier that shadows built-ins.
  • Automatically detect use of reserved words with the keyword module.
  • Write test cases to ensure renamed logic still behaves as expected.

Task 2: Build a Keyword Checker Tool

Create a small utility that accepts a string of Python code (via input or a multi-line string), parses it, and detects whether any keywords were misused as identifiers. For example, someone might write if = 5 which would break the code. Your program should detect and warn about such problems.

What this Task Teaches

You’ll gain experience working with Python’s parsing tools and keyword detection. This task mimics the behavior of linters or static analyzers and helps you build safe coding habits by detecting mistakes automatically.

Hints and Tips
  • Use the keyword module’s iskeyword() function.
  • You may use split() and basic pattern matching to extract potential variable names.
  • Focus on simple assignment lines like x = 10.
Common Mistakes
  1. Overcomplicating the parser: You don’t need a full parser — just look for identifier = value patterns.
  2. Missing edge cases: Look for common keyword mistakes like for, class, or def used as variables.
  3. Confusing invalid identifiers with keywords: Some invalid names aren’t keywords — like 2name.
  4. Not displaying useful warnings: Your tool should print a message for every suspicious name.
  5. Hardcoding checks: Always rely on keyword.iskeyword() for flexibility and future compatibility.
Step-by-Step Thinking

You're simulating a basic static analyzer. Aim for flexibility and accuracy.

  1. Accept input: a list of code lines or a multi-line string
  2. Split each line into tokens (e.g., using split())
  3. Find tokens before the = sign
  4. Check if the token is a Python keyword using keyword.iskeyword()
  5. If yes, display a warning: “Invalid identifier: 'if' is a keyword”
How to Make it Harder
  • Use the ast module to parse code safely and detect identifiers more accurately.
  • Extend your checker to scan entire Python files.
  • Display line numbers and error types like a real linter.