Python Identifiers and Reserved Words

An identifier in Python is just a name that we give to things like variables, functions, classes, or modules. It helps Python understand what we’re referring to in our code.

Rules for Identifiers in Python:

  1. We can only use letters (uppercase or lowercase), numbers (0 to 9), or underscores (_) in identifiers. If we use any other symbol like ‘$’, Python won’t understand it and will show an error.
    • For example: cash = 10 # This is okay
    • ca$h = 20 # This is not okay
  2. Identifiers can’t start with a number. They can start with a letter or an underscore.
    • For example: code123total # This is not okay
    • total123 # This is okay
  3. Python cares about capitalization, so uppercase and lowercase letters are different.
    • For example:total = 10 TOTAL = 999 print(total) # This will print 10
    • print(TOTAL) # This will print 999
  4. We can’t use reserved words (words that Python already uses for its own purposes) as identifiers.
    • For example: def = 10 # This is not okay
  5. There’s no limit to how long an identifier can be, but it’s best to keep them reasonably short.
  6. Symbols like ‘$’ are not allowed in Python identifiers.

Valid Identifiers in Python:

  • They can be letters, numbers, or underscores.
  • If an identifier starts with an underscore, it usually means it’s private.
  • They can’t start with a number.
  • Python pays attention to capitalization.
  • We can’t use reserved words as identifiers.

Notes:

  1. If an identifier starts with ‘_’ (underscore), it usually means it’s private.
  2. If it starts and ends with two underscores, it’s a special name defined by Python.
  3. Reserved words are words that Python already uses for specific purposes.

Reserved Words

Reserved words in Python have special meanings or functions. There are 33 reserved words in Python:

pythonCopy codeTrue, False, None
and, or, not, is
if, elif, else
while, for, break, continue, return, in, yield
try, except, finally, raise, assert
import, from, as, class, def, pass, global, nonlocal, lambda, del, with

Notes:

  1. All reserved words in Python are made up only of letters.
  2. Except for ‘True’, ‘False’, and ‘None’, all reserved words are written in lowercase.

Examples:

a = true  # This is not okay
a = True # This is okay

To see all the reserved words in Python, we can use the ‘keyword’ module:

import keyword
print(keyword.kwlist)

This will show us all the reserved words that Python uses.

Leave a comment