Board Formulas
🐍 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
python
import 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
python
class 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