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:
- Python syntax rules
- How variables and identifiers are used
- What Python keywords are and why they cannot be reused
- Rules for valid identifiers: lowercase, no spaces, no keywords, no special characters
- Best practices: use meaningful, descriptive names for identifiers
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
- Using numbers at the start of names: Identifiers can’t begin with a digit —
1name
is invalid. - Including hyphens: Use underscores instead —
first-name
will cause a syntax error. - Using Python keywords: Names like
for
,if
, ordef
cannot be reused for variables. - Assuming built-in functions are okay to overwrite: Avoid using names like
list
orstr
even though they're technically valid. - Forgetting case sensitivity:
Name
andname
are different variables.
Step-by-Step Thinking
You’re validating names. Focus on the rules Python enforces for identifiers.
- Iterate over the list of names
- Use
isidentifier()
to check each one - Print the name and whether it’s valid
- Optionally, write a comment for each invalid name to explain why
- 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
- Keeping keyword names unchanged: Variables like
class
ordef
must be renamed completely. - Adding numbers without context: Instead of
value1
, preferinitial_value
or something meaningful. - Leaving spaces or dashes: Identifiers must use only underscores — no spaces or punctuation.
- Using vague names: While fixing names, make sure they still reflect their purpose.
- 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.
- Look for issues: keyword usage, numbers at the start, symbols, or spaces
- Replace illegal parts with legal ones (e.g., hyphens → underscores)
- Rename keywords to something descriptive (e.g.,
class → class_name
) - Write a comment beside each fix to explain your change
- 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()
andkeyword.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
orsum
. - Use descriptive names like
numbers
ortotal
instead. - Think about what each identifier represents and name it accordingly.
Common Mistakes
-
Shadowing built-ins: Redefining
sum
means you lose access to Python’s originalsum()
function — a common and serious mistake. - Generic names like “list”: While valid, they confuse readers and overlap with core concepts.
- Reusing vague names in different contexts: A name like
result
is fine, but it should be more specific if multiple results exist. - Not updating all usages after renaming: If you change
list
tonumbers
, make sure it’s changed everywhere. - 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.
- Identify names that match Python built-ins or keywords
- Rename the function from
sum
to something likecalculate_sum
- Rename
list
tonumbers
orvalues
- Make sure the internal variable
result
clearly describes the output - 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 usekeyword.iskeyword()
to check if it's a keyword.
Common Mistakes
-
Forgetting to import the
keyword
module: Theiskeyword()
method won’t work without it. - Confusing keywords and invalid identifiers: A keyword like
if
is a valid identifier by syntax, but still unusable as a name. - Incorrect string formatting: Use f-strings for clearer output messages (e.g.,
f"{name} is a keyword"
). - Not checking case sensitivity:
If
andif
are different — only the lowercase one is a keyword. - Skipping edge cases: Test inputs like
""
,123
,__init__
, andNone
.
Step-by-Step Thinking
This program acts as a mini validation tool. You need to process user input and classify it with clear feedback.
- Ask the user to input a string
- Check if it’s a valid identifier using
isidentifier()
- Import the
keyword
module - Check if the input is a keyword using
iskeyword()
- 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 ofsum
. - Avoid naming anything
input
,max
, orclass
. - Add comments explaining each change for future developers.
Common Mistakes
-
Keeping function names like
max
: This disables use of the originalmax()
function elsewhere in your code. - Using reserved words: Names like
class
are illegal and will crash your program. - Renaming without consistency: If you rename
sum
tototal
, update it everywhere. - Forgetting to test after refactoring: Even a small typo can break logic after renaming variables.
- 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.
- Scan for any names that match built-in functions or keywords
- Refactor each one with meaningful, safe alternatives (e.g.,
max → get_max_value
) - Add a comment next to each change explaining the reason
- Check that the logic still runs correctly with updated names
- 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’siskeyword()
function. - You may use
split()
and basic pattern matching to extract potential variable names. - Focus on simple assignment lines like
x = 10
.
Common Mistakes
- Overcomplicating the parser: You don’t need a full parser — just look for
identifier = value
patterns. - Missing edge cases: Look for common keyword mistakes like
for
,class
, ordef
used as variables. - Confusing invalid identifiers with keywords: Some invalid names aren’t keywords — like
2name
. - Not displaying useful warnings: Your tool should print a message for every suspicious name.
- 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.
- Accept input: a list of code lines or a multi-line string
- Split each line into tokens (e.g., using
split()
) - Find tokens before the
=
sign - Check if the token is a Python keyword using
keyword.iskeyword()
- 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.