September 11, 2024

Python Keywords

Python keywords are reserved words that have special meanings in the language. These keywords form the foundation of Python’s syntax and cannot be used as identifiers (variable names, function names, etc.). They are case-sensitive, and each plays a specific role in the language.

Here’s an in-depth look at Python keywords:

List of Python Keywords

As of Python 3.10 (which is current as of my last update), here’s the complete list of Python keywords:

Here’s a table listing all Python keywords:

Keyword Description
False Boolean value indicating falsehood.
True Boolean value indicating truth.
None Represents the absence of a value or a null value.
and Logical operator to combine conditional statements.
as Used to create an alias or for exception handling.
assert Debugging aid that tests a condition.
async Declares a function to be asynchronous.
await Pauses asynchronous function execution until a task finishes.
break Exits the nearest enclosing loop immediately.
class Defines a new class.
continue Skips the rest of the loop and starts the next iteration.
def Defines a new user-defined function.
del Deletes objects, variables, or items from a list.
elif Else if; used in conditional statements.
else Defines an alternative block of code in a condition.
except Handles exceptions raised by try.
finally Executes code regardless of whether an exception occurs.
for Loops over a sequence of values.
from Imports specific attributes from a module.
global Declares a variable as global.
if Conditional statement to execute code based on a condition.
import Imports a module into the current namespace.
in Checks if a value is present in a sequence.
is Tests for object identity (same object in memory).
lambda Creates a small anonymous function.
nonlocal Declares a variable as not local to the current function.
not Logical operator that inverts the truth value.
or Logical operator to combine conditional statements.
pass Null statement; does nothing.
raise Raises an exception.
return Exits a function and optionally returns a value.
try Tests a block of code for errors.
while Loops while a condition is true.
with Simplifies exception handling by wrapping code execution.
yield Pauses a function and returns a generator.

Explanation of Each Keyword

  1. False / True:
    • Boolean values in Python. They represent the two truth values in Python.
    • Example:

    is_valid = True
    is_empty = False

  2. None:
    • Represents the absence of a value or a null value.
    • Example:

    result = None

  3. and / or / not:
    • Logical operators used to combine conditional statements.
    • Example:

    if a > 0 and b > 0:
    print("Both are positive")

  4. as:
    • Used to create an alias when importing a module or for exception handling.
    • Example:

    import math as m

    5.assert:

    • Used for debugging purposes, to test if a condition in your code returns True. If not, an AssertionError is raised.
    • Example:

    assert x > 0, "x must be positive"

    6.async / await:

    • Used in asynchronous programming to define asynchronous functions and handle asynchronous operations.
    • Example:

    async def fetch_data():
    await some_async_function()

    7.break:

    • Terminates the nearest enclosing loop, exiting the loop immediately.
    • Example:

    for i in range(10):
    if i == 5:
    break

    8.class:

    • Used to define a new user-defined class.
    • Example:

    class MyClass:
    pass

    9.continue:

    • Skips the rest of the code inside the loop for the current iteration and jumps to the next iteration of the loop.
    • Example:

    for i in range(10):
    if i % 2 == 0:
    continue
    print(i)

    10.def:

    • Used to define a new user-defined function.
    • Example:

    def my_function():
    pass

    11.del:

    • Deletes objects or variables.
    • Example:

    x = 10
    del x

    12.elif:

    • Stands for “else if” and is used in conditional statements to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.
    • Example:

    if x < 0:
    print("Negative")
    elif x == 0:
    print("Zero")
    else:
    print("Positive")

    13.else:

    • Used in conditional statements or loops. It is executed if the previous conditions were False.
    • Example:

    if x < 0:
    print("Negative")
    else:
    print("Non-negative")

    14.except:

    • Used with try to handle exceptions. Code under except is executed if an error occurs in the try block.
    • Example:

    try:
    result = 10 / 0
    except ZeroDivisionError:
    print("Cannot divide by zero")

    15.finally:

    • Used with try to execute a block of code no matter if an exception occurred or not.
    • Example:

    try:
    result = 10 / 0
    except ZeroDivisionError:
    print("Cannot divide by zero")
    finally:
    print("This will run no matter what")

    16.for:

    • Used to create a for loop, which iterates over a sequence (like a list, tuple, or string).
    • Example:

    for i in range(5):
    print(i)

    17.from / import:

    • import is used to bring in modules into your current namespace.
    • from is used to import specific attributes or functions from a module.
    • Example:

    import math
    from math import sqrt

    18.global:

    • Declares that a variable inside a function is global (i.e., it can be modified outside the function as well).
    • Example:

    x = 10
    def change():
    global x
    x = 20
    change()
    print(x) # Output: 20

    19.if:

    • Used for conditional branching.
    • Example:

    if x > 0:
    print("Positive")

    20.in:

    • Checks if a value exists within a sequence (such as a list, tuple, or string).
    • Example:

    if "a" in "apple":
    print("Found")

    21.is:

    • Tests for object identity (whether two references point to the same object in memory).
    • Example:

    a = [1, 2, 3]
    b = a
    print(a is b) # Output: True

    22.lambda:

    • Used to create small anonymous functions.
    • Example:

    square = lambda x: x * x
    print(square(5)) # Output: 25

    23.nonlocal:

    • Declares that a variable is not local to the current function, but rather belongs to the nearest enclosing scope that is not global.
    • Example:

    def outer():
    x = "outer"
    def inner():
    nonlocal x
    x = "inner"
    inner()
    print(x) # Output: inner
    outer()

    24.not:

    • Logical operator that inverts the value of a boolean expression.
    • Example:

    x = True
    print(not x) # Output: False

    25.pass:

    • A null statement; it does nothing. It’s a placeholder in loops, functions, classes, or conditionals where you don’t want any action to be performed.
    • Example:

    def my_function():
    pass

    26.raise:

    • Used to raise an exception.
    • Example:

    raise ValueError("An error occurred")

    27.return:

    • Exits a function and optionally passes an expression back to the caller.
    • Example:

    def add(a, b):
    return a + b

    28.try:

    • Specifies a block of code to be tested for errors while it is being executed.
    • Example:

    try:
    result = 10 / 0
    except ZeroDivisionError:
    print("Cannot divide by zero")

    29.while:

    • Used to create a loop that repeats as long as a condition is true.
    • Example:

    i = 0
    while i < 5:
    print(i)
    i += 1

    30.with:

    • Used to wrap the execution of a block of code within methods defined by a context manager (e.g., managing resources like files).
    • Example:

    with open('file.txt', 'r') as file:
    content = file.read()

    31.yield:

    • Used inside a function like return, but returns a generator instead of a single value.
    • Example:

    def generator():
    yield 1
    yield 2
    yield 3

    for value in generator():
    print(value)

Understanding Keyword Usage

  • Control Flow Keywords: if, elif, else, for, while, break, continue, pass, try, except, finally, raise, return, yield, with, assert.
  • Function and Class Definitions: def, class, lambda, return.
  • Logical Operations: and, or, not, is, in.
  • Variable Scoping: global, nonlocal.
  • Asynchronous Programming: async, await.

Checking for Keywords

You can check if a word is a Python keyword using the keyword module:
import keyword
print(keyword.iskeyword("if")) # Output: True
print(keyword.iskeyword("hello")) # Output: False

You can also get the list of all keywords using:
print(keyword.kwlist)

Best Practices

  • Avoid Using Keywords as Identifiers: Since keywords have special meanings, avoid using them as variable or function names to prevent syntax errors.
  • Understand Each Keyword: Before using a keyword, make sure you understand its purpose and how it affects the flow of your program.
  • Use IDEs and Text Editors: Modern IDEs and text editors highlight keywords in a different color, which helps in writing error-free code.

Understanding Python keywords and their functions is crucial for writing effective Python programs. They form the core of Python’s syntax and provide the necessary tools to control the flow of your program, handle exceptions, and define structures like functions and classes.