In Python, keywords are reserved words that have special meanings and purposes within the language.
we don't need to import any keyword into our code snippets because they're already present.
These keywords cannot be used as identifiers (such as variable names, function names, or class names) because they are part of the language syntax.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and classes are constantly present; however, they are not as limited in their application as keywords.
We will get a SyntaxError message, if we try to re-declare reserved words in our code snippet.
Here is a list of Python keywords:
True False if else elif from None break except raise class finally is return and continue for lambda try while def pass nonlocal as assert del global in not with async import await or yield
# Output: ['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']
# import keyword library which contains lists of reserve keywords. import keyword # print the list using kwlist. print(keyword.kwlist)
We can also check the list of keywords programmatically using the keyword module in Python:
True, False: Boolean types represent Boolean values True and False.
if, elif, else: Conditional statements for executing conditions based code.
and, or, not: Logical operators for conjunction, disjunction, and negation.
for, while: Loops for iterate over sequences (like lists, tuples, or dictionaries) or executing code block repeatedly.
break, continue: Used inside loops to exit the loop prematurely (break) or skip the current iteration and continue with the next one (continue).
def, return: def keyword is used to define functions in Python and the `return` keyword returns values from functions.
class, pass, del: class keyword is used to define classes, pass is a null operation (useful as a placeholder), and del keyword is used to delete objects.
try, except, finally, raise: `catch` block handles an exception if it occurs in `try` block, finally block runs once when `try` block or `catch` block gets executed, raise exceptions.
None: represent null value None
global, nonlocal: Used to declare global and non-local variables inside functions.
lambda: Used to create anonymous functions (functions without a name).
import, from, as: import and from are used to import modules, and as is used for aliasing.
yield: Used in generator functions to produce a sequence of values.
Note: These keywords are an integral part of the Python language and are used to define the structure and behaviour of Python code, such as control flow statements, variable declarations, defining functions and classes, and more.