π Pythonπ
Day 3
Identifiers & Keywords in Python
Rules for naming identifiers, the list of Python keywords, and PEP 8 naming conventions.
π―
Learning objectives
- βWrite valid Python identifiers
- βKnow the reserved keywords
- βFollow PEP 8 naming conventions
π‘ Key points
- Identifier = name of a variable, function, class, module, etc.
- Rules: start with letter or _; then letters, digits or _; case-sensitive; no keywords.
- Use keyword.kwlist to see all reserved keywords at runtime.
- PEP 8: snake_case for functions/vars, PascalCase for classes, UPPER_CASE for constants.
π» Code examples(3)
#1Valid vs invalid identifiers
python# valid
age = 21
user_name = "Amit"
_private = 10
score1 = 90
# invalid β raise SyntaxError
# 1st_name = "x" # starts with digit
# user-name = "x" # hyphen not allowed
# class = "x" # reserved keyword
Underscore is allowed anywhere. Hyphens are illegal. Reserved keywords cannot be reused.
#2Check keywords programmatically
pythonimport keyword
print(keyword.kwlist)
print(keyword.iskeyword("for")) # True
print(keyword.iskeyword("foo")) # False
The keyword module always reflects the current interpreter's reserved words.
#3PEP 8 naming conventions
pythonclass BankAccount: # class β PascalCase
MIN_BALANCE = 500 # constant β UPPER_CASE
def __init__(self, holder):
self.account_holder = holder # attribute β snake_case
def calculate_interest(self): # method β snake_case
return 0.05
π― Practice
Q1. Is `_secret` a valid identifier? What about `__secret__`?+
Both are valid. Single leading _ is a 'weak private' convention. Double underscores on both sides (dunder) are reserved for Python special methods β do not invent your own.
Q2. List three reserved keywords in Python.+
Any three of: False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
Q3. Rename this to follow PEP 8: def CalculateTax(): ...+
def calculate_tax(): ... β functions use snake_case, not PascalCase.
π Notes
Reserved keywords
False None True and as assert async await
break class continue def del elif else except
finally for from global if import in is
lambda nonlocal not or pass raise return try
while with yield
PEP 8 quick cheat
- Variables / functions:
snake_caseβtotal_marks,read_file() - Classes:
PascalCaseβStudentRecord - Constants:
UPPER_CASEβMAX_RETRIES - Modules/packages: lower snake β
data_utils - Private hint: leading
_β_internal_helper