Python Invalid Identifiers
🧠 In Python, there’s a fixed list of keywords that cannot be used as identifiers (i.e., names for variables, functions, classes, etc.). They are reserved because they have a special meaning in the language core.
🛑 Invalid Identifiers: Python Keywords #
Here’s the complete list of reserved keywords in Python 3. You must not use these as names for variables, functions, or classes:
import keyword
print(keyword.kwlist)
📜 List of Keywords (Python 3.11+) #
| Category | Keywords |
|---|---|
| Control | if, else, elif, while, for, break, continue, pass |
| Definitions | def, class, lambda, return, yield |
| Logic & Comparison | and, or, not, is, in |
| Error Handling | try, except, finally, raise, assert |
| Import & Modules | import, from, as, global, nonlocal |
| Data & Types | True, False, None |
| Miscellaneous | del, with, await, async, match, case |
🚫 Examples of Invalid Identifiers #
def if(): # ❌ Invalid: "if" is a keyword
pass
class None: # ❌ Invalid: "None" is a special value
lambda = 5 # ❌ Invalid: "lambda" is a keyword
✅ Instead, use descriptive names like user_if, no_values, lambda_value.
✅ Valid Identifiers – Rules #
A valid identifier:
- Starts with a letter or underscore (
_) - Consists only of letters, digits, and underscores
- Must not be a keyword
✔️ Examples: #
name = "Lena"
_count = 5
grade1 = 2
❌ Invalid Identifiers: #
1name = "Tom" # ❌ starts with number
def = "Function" # ❌ keyword
🧠 Tip for Students: #
If you’re unsure whether a word is allowed, you can check it:
import keyword
print(keyword.iskeyword("def")) # Output: True