2.2.1 Identifiers & Keywords
In Python, some words are reserved by the Python language developers. These words are called keywords or reserved words.
Each keyword has a predefined meaning and functionality in Python. Since Python already uses these words for specific purposes, we cannot use them as variable names, function names, or class names.
For example, keywords like if, else, for, while, and class have special meanings in Python.
When we create variables to store values, we must choose names that are different from these reserved words.
Example
Valid variable names:
age = 20
name = "Ali"
total_marks = 95
❌ Invalid variable names:
if = 20
for = 10
class = "Math"
These produce errors because if, for, and class are Python keywords.
You can see all Python keywords with:
import keyword
print(keyword.kwlist)
The Complete List of Keywords
As of Python 3.12, there are 35 keywords.
| Category | Keywords |
|---|---|
| Value Keywords | True, False, None |
| Logical Operators | and, or, not, in, is |
| Control Flow | if, elif, else, for, while, break, continue, pass |
| Function/Class | def, return, lambda, class |
| Exception Handling | try, except, finally, raise, assert |
| Import/Scope | import, from, as, global, nonlocal |
| Async Programming | async, await |
| Miscellaneous | with, del, yield |
Key Characteristics
- Case Sensitivity: Most keywords are lowercase (e.g.,
if,while). However, three start with a capital letter:True,False, andNone. - Immutability: You cannot redefine keywords. Trying to assign a value to one (e.g.,
pass = 5) will result in aSyntaxError. - Context: Some keywords only work in specific contexts. For example,
returncan only be used inside a function, andawaitcan only be used inside anasyncfunction.
Common Keywords Explained
1. Control Flow (if, elif, else)
These are used for decision-making.
if x > 10:
print("Large")
else:
print("Small")
2. Loops (for, while, break, continue)
Used to repeat blocks of code. break exits a loop early, while continue skips to the next iteration.
3. Structural Keywords (def, class)
def: Used to define a new function.class: Used to define a new user-defined object (Class).
4. Logical Operators (and, or, not)
Used to combine conditional statements. These are much more readable in Python than the && or || used in other languages.
lightbulbPro Tip: In most code editors (like VS Code or PyCharm), keywords will automatically change color (usually blue or purple) to alert you that they are reserved. If your variable name turns a bright color, you should probably rename it!