2 min read

Keywords and Identifiers in Python 3

Learn about reserved keywords, identifiers, and their usage in Python 3.
Keywords and Identifiers in Python 3
Keywords and Identifiers in Python

What are Python Keywords?

Python keywords are reserved words in Python. These keywords cannot be used to name objects in Python like variables, functions, and classes.

Keywords in Python are case-sensitive.

The following is a list of reserved keywords in Python 3.9.

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

A simple use case of if-else in Python

An if else statement in Python evaluates whether an expression is true or false.

Code

num = 5

if num%2 == 0:
    print("It is Even")
else:
    print("It is odd")

Output

It is odd

The above example uses if and else reserved keywords to implement the odd-even identifier.

How to check if a string is a keyword?

Python provides a keyword module that allows you to check for reserved keywords.

Code/Output

import keyword

print(keyword.iskeyword("for"))
>>> True

print(keyword.iskeyword("str"))
>>> False

You could also get a list of all reserved keywords in Python using the kwlist attribute in the keyword module.

Code/Output

import keyword

print(keyword.kwlist)
>>> ['False', 'None', 'True', '__peg_parser__', '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']

Python Identifiers

Identifiers are the opposite of reserved keywords.

They are names that users can choose to name their variables, functions, and classes.

Rules to remember while writing identifiers

  1. They can be a combination of lowercase and uppercase letters (A to Z), numbers (0 to 9) and underscore(_).
    Valid Examples - x, my_list, str123
  2. Identifiers cannot start with a number.
    Invalid example - 1name
    Valid Example - name1
  3. Keywords cannot be used as identifiers.
  4. Special symbols like !, @, #, $, % etc. cannot be used.
    x@ = 1
    >>> SyntaxError: invalid syntax
    

Examples of Valid Identifiers

  1. myvar1
  2. myvar_1
  3. _myvar1
  4. _1_myvar

Examples of Invalid Identifiers

  1. @myvar1
  2. 1myvar
  3. 1_myvar
  4. myvar@1

Final Suggestions

  1. Python is case-sensitive. This means X and x are not the same.
  2. Use variable, function, and class names that are descriptive of its functionality.
  3. Use snake case to write long variables. Example - my_int_only_list.