;

Python Keywords


Python is a powerful and versatile programming language known for its readability and simplicity. One of the foundational aspects of Python is its set of keywords—reserved words that have special meanings and are integral to the language's syntax. Understanding these keywords is essential for writing effective Python code. In this comprehensive tutorial, we'll explore all the Python keywords up to version 3.13.0, explain their functions, provide examples, and discuss their use cases.

What Are Python Keywords?

Python keywords are reserved words that have predefined meanings and syntactic significance. They cannot be used as identifiers (variable names, function names, etc.) in your code. Keywords define the language's structure and are essential for writing syntactically correct Python programs.

List of Python Keywords

Below is a table of all Python keywords up to version 3.13.0, along with brief descriptions and examples.

Keyword

Description

Example

False

Boolean false value

is_raining = False

True

Boolean true value

is_sunny = True

None

Represents the absence of a value

result = None

and

Logical AND operator

if a > 0 and b > 0:

or

Logical OR operator

if a > 0 or b > 0:

not

Logical NOT operator

if not is_empty:

is

Identity operator

if a is b:

in

Membership operator

if item in list:

if

Starts a conditional statement

if score >= 90:

elif

Else if; additional condition

elif score >= 80:

else

Default block if conditions are false

else:

for

Starts a for loop

for i in range(5):

while

Starts a while loop

while condition:

break

Exits the nearest loop

break

continue

Skips to the next iteration of loop

continue

pass

Does nothing; placeholder

def function(): pass

def

Defines a function

def greet(name):

return

Returns a value from a function

return result

lambda

Creates an anonymous function

lambda x: x * 2

class

Defines a class

class MyClass:

del

Deletes objects

del variable

global

Declares a global variable

global count

nonlocal

Declares a non-local variable

nonlocal total

try

Starts a try block for exceptions

try:

except

Catches exceptions

except ValueError:

finally

Executes code regardless of exceptions

finally:

raise

Raises an exception

raise Exception("Error")

assert

Asserts a condition

assert x > 0, "x must be positive"

import

Imports modules

import math

from

Imports specific parts of a module

from math import sqrt

as

Renames a module or variable

import numpy as np

with

Simplifies exception handling

with open('file.txt') as f:

async

Declares an asynchronous function

async def fetch_data():

await

Awaits an asynchronous call

data = await fetch_data()

yield

Returns a generator object

yield value

match

Starts a pattern matching block

match variable:

case

Defines a pattern in match statements

case 1:

__peg_parser__

Special parser keyword (3.9+)

Internal use; no direct code example

Detailed Explanation of Python Keywords

Let's delve deeper into each keyword, understand its purpose, and see how it fits into Python programming.

False, True, None

False and True

These are the Boolean values in Python, representing false and true respectively.

Example:

is_active = True
if is_active:
    print("The system is active.")
else:
    print("The system is inactive.")
Explanation:
  • is_active is set to True.
  • The if statement checks if is_active is True.
  • The corresponding message is printed based on the Boolean value.

None

Represents the absence of a value or a null value.

Example:

result = None
if result is None:
    print("No result available.")
Explanation:
  • result is assigned None.
  • Using is to check if result is None.

and, or, not, is, in

Logical Operators

  • and: Returns True if both operands are true.
  • or: Returns True if at least one operand is true.
  • not: Inverts the truth value.

Example:

a = 10
b = 20
if a > 5 and b > 15:
    print("Both conditions are True.")
Explanation:
  • Checks if both a > 5 and b > 15 are True.

Identity Operator is

Checks if two variables point to the same object.

Example:

a = [1, 2, 3]
b = a
print(a is b)  # Output: True
Explanation:
  • b references the same list as a.
  • is checks for object identity.

Membership Operator in

Checks if a value is present in a sequence.

Example:

fruits = ['apple', 'banana', 'cherry']
if 'banana' in fruits:
    print("Banana is in the list.")
Explanation:
  • Checks if 'banana' is an element of the fruits list.

if, elif, else

Used for conditional branching.

Example:

score = 85
if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")
else:
    print("Grade C")
Explanation:
  • Checks conditions in order.
  • Executes the block where the condition is True.

for, while, break, continue, pass

for Loop

Iterates over a sequence.

Example:

for i in range(5):
    print(i)
Explanation:
  • Prints numbers from 0 to 4.

while Loop

Repeats as long as a condition is true.

Example:

count = 0
while count < 5:
    print(count)
    count += 1
Explanation:
  • Similar to the for loop example but using while.

break

Exits the nearest enclosing loop.

Example:

for i in range(10):
    if i == 5:
        break
    print(i)
Explanation:
  • Stops the loop when i equals 5.

continue

Skips the rest of the code inside the loop for the current iteration.

Example:

for i in range(5):
    if i == 2:
        continue
    print(i)
Explanation:
  • Skips printing when i is 2.

pass

Does nothing; acts as a placeholder.

Example:

def function():
    pass  # Function implementation will be added later
Explanation:
  • Allows you to write empty code blocks.

def, return, lambda

def

Defines a function.

Example:

def add(a, b):
    return a + b
Explanation:
  • Defines a function add that returns the sum of a and b.

return

Exits a function and returns a value.

Example:

def square(x):
    return x * x
Explanation:
  • Returns the square of x.

lambda

Creates an anonymous function.

Example:

double = lambda x: x * 2
print(double(5))  # Output: 10
Explanation:
  • lambda x: x * 2 defines an anonymous function that doubles the input.

class, del, global, nonlocal

class

Defines a class.

Example:

class Person:
    def __init__(self, name):
        self.name = name
Explanation:
  • Defines a class Person with an initializer method.

del

Deletes objects.

Example:

x = 10
del x
Explanation:
  • Deletes the variable x from the namespace.

global

Declares a global variable inside a function.

Example:

count = 0

def increment():
    global count
    count += 1
Explanation:
  • Modifies the global variable count inside the function.

nonlocal

Declares a non-local variable inside nested functions.

Example:

def outer():
    x = 5
    def inner():
        nonlocal x
        x = 10
    inner()
    print(x)  # Output: 10
Explanation:
  • Modifies the variable x in the outer function from within inner.

try, except, finally, raise, assert

Exception Handling

  • try: Wraps code that might raise an exception.
  • except: Catches exceptions.
  • finally: Executes code regardless of exceptions.
  • raise: Raises an exception.
  • assert: Asserts that a condition is true.

Example:

try:
    x = int(input("Enter a number: "))
except ValueError:
    print("Invalid input.")
else:
    print(f"You entered {x}")
finally:
    print("Execution complete.")
Explanation:
  • Tries to convert user input to an integer.
  • Catches ValueError if conversion fails.
  • else block runs if no exception occurs.
  • finally block runs regardless.

raise

Example:

def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero.")
    return a / b
Explanation:
  • Raises an exception if b is zero.

assert

Example:

def square_root(x):
    assert x >= 0, "x must be non-negative"
    return x ** 0.5
Explanation:
  • Checks that x is non-negative before proceeding.

import, from, as

Module Importing

  • import: Imports a module.
  • from: Imports specific attributes from a module.
  • as: Renames the module or attribute.

Example:

import math
print(math.pi)

from math import sqrt
print(sqrt(16))

import numpy as np
Explanation:
  • Imports the entire math module.
  • Imports only the sqrt function from math.
  • Imports numpy and aliases it as np.

with, async, await

with

Simplifies exception handling by encapsulating common preparation and cleanup tasks.

Example:

with open('file.txt', 'r') as file:
    content = file.read()
Explanation:
  • Automatically handles file closing.

async and await

Used for asynchronous programming.

Example:

import asyncio

async def fetch_data():
    await asyncio.sleep(1)
    return "Data received"

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())
Explanation:
  • Defines asynchronous functions using async.
  • await pauses execution until the awaited task is complete.

yield

Used in generator functions to return a value and pause execution.

Example:

def generator():
    for i in range(3):
        yield i

for value in generator():
    print(value)
Explanation:
  • generator() yields values one at a time.
  • The for loop retrieves each value.

match, case

Introduced in Python 3.10 for structural pattern matching.

Example:

def http_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Unknown Status"

print(http_status(404))  # Output: Not Found
Explanation:
  • match checks the value of status.
  • case matches specific patterns.
  • _ is a wildcard for any value.

Key Takeaways

  • Understanding Keywords: Python keywords are reserved words with special meanings that form the language's syntax.
  • Cannot Be Used as Identifiers: Keywords cannot be used as variable names or identifiers.
  • Categories of Keywords:
    • Control Flow: if, else, for, while, etc.
    • Data Handling: def, class, lambda, etc.
    • Exception Handling: try, except, finally, raise, assert.
    • Logical Operators: and, or, not, is, in.
  • New Additions: match and case were introduced in Python 3.10 for pattern matching.
  • Asynchronous Programming: async and await facilitate concurrent execution.

Summary

Python keywords are the building blocks of Python programming. They define the language's structure and enable developers to write clear and efficient code. By understanding each keyword's purpose and how to use it, you can leverage Python's full capabilities.

In this guide, we've covered all the Python keywords up to version 3.13.0, explained their functions, and provided practical examples. Whether you're controlling program flow with if and for, handling exceptions with try and except, or writing asynchronous code with async and await, knowing these keywords is essential.

Keep this guide as a reference as you continue your Python journey. Happy coding!