Back to Study Material Python

Keywords

Keywords are reserved words that have a fixed, special meaning in Python. You cannot use them as variable names, function names, or any other identifier. P...

Keywords

What are Keywords?

Keywords are reserved words that have a fixed, special meaning in Python. You cannot use them as variable names, function names, or any other identifier. Python 3.12 has 35 keywords. You can see all of them by importing the keyword module and printing keyword.kwlist. Examples include if, else, elif, for, while, def, class, return, import, from, True, False, None, and, or, not, in, is, lambda, pass, break, continue, and global.

Control Flow Keywords

Several keywords control execution flow. if, elif, and else define conditional branches. for and while create loops. break exits a loop immediately. continue skips the current iteration and moves to the next one. pass is a placeholder that does nothing (useful when a syntactically required block has no code yet). return exits a function and optionally sends a value back to the caller. yield suspends a function and produces a value for a generator.

Exception Keywords

Python uses try, except, else, finally, raise, and assert to handle exceptions. Code that might fail goes inside a try block. Exceptions are caught in except clauses. The else block runs if no exception occurred. The finally block runs regardless of whether an exception occurred — it is used for cleanup like closing files or database connections. raise manually triggers an exception. assert checks a condition and raises AssertionError if it is False.

Import and Scope Keywords

import and from are used to load modules and specific names from them: import math; from math import sqrt. global declares that a name inside a function refers to the module-level (global) variable. nonlocal declares that a name inside a nested function refers to a variable in the enclosing (but not global) scope. del removes a name from the current namespace or deletes an element from a list or dictionary.

Special Value Keywords

True and False are the two boolean literals. They are capitalized; true and false are not recognized as keywords. None represents the absence of a value, similar to null in other languages. A function that does not explicitly return a value actually returns None automatically. lambda creates anonymous (inline) functions. async and await are keywords that support asynchronous programming with the asyncio framework.

Exam Tip

Exams test keyword knowledge in subtle ways. A common question: can you use list, dict, or str as a variable name? Technically yes — they are built-in names, not keywords, so Python does not prevent it. However, doing so shadows the built-in type and is considered very bad practice. Another question: what does the else clause on a for loop do? It runs after the loop completes normally (without a break). This is an unusual feature that trips up many students.