Theory of Intelligence
PYTHON PROGRAMMING•Foundations•Syntax Basics•2.2 Identifiers, Keywords & Variables

2.2.1 Identifiers & Keywords

Subtopics: Identifiers & Keywords, Variables and Assignment.

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:

PYTHON
age = 20
name = "Ali"
total_marks = 95

❌ Invalid variable names:

PYTHON
if = 20
for = 10
class = "Math"

These produce errors because if, for, and class are Python keywords.

You can see all Python keywords with:

PYTHON
import keyword
print(keyword.kwlist)

The Complete List of Keywords

As of Python 3.12, there are 35 keywords.

CategoryKeywords
Value KeywordsTrue, False, None
Logical Operatorsand, or, not, in, is
Control Flowif, elif, else, for, while, break, continue, pass
Function/Classdef, return, lambda, class
Exception Handlingtry, except, finally, raise, assert
Import/Scopeimport, from, as, global, nonlocal
Async Programmingasync, await
Miscellaneouswith, del, yield

Key Characteristics

  • Case Sensitivity: Most keywords are lowercase (e.g., if, while). However, three start with a capital letter: True, False, and None.
  • Immutability: You cannot redefine keywords. Trying to assign a value to one (e.g., pass = 5) will result in a SyntaxError.
  • Context: Some keywords only work in specific contexts. For example, return can only be used inside a function, and await can only be used inside an async function.

Common Keywords Explained

1. Control Flow (if, elif, else)

These are used for decision-making.

PYTHON
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.

lightbulb

Pro 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!

Discuss theoretical concepts, mathematical formulas, and architectural foundations.

Supports inline code with `backticks`
No comments yet. Be the first to start the discussion!