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.
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.
Below is a table of all Python keywords up to version 3.13.0, along with brief descriptions and examples.
Keyword |
Description |
Example |
|
Boolean false value |
|
|
Boolean true value |
|
|
Represents the absence of a value |
|
|
Logical AND operator |
|
|
Logical OR operator |
|
|
Logical NOT operator |
|
|
Identity operator |
|
|
Membership operator |
|
|
Starts a conditional statement |
|
|
Else if; additional condition |
|
|
Default block if conditions are false |
|
|
Starts a for loop |
|
|
Starts a while loop |
|
|
Exits the nearest loop |
|
|
Skips to the next iteration of loop |
|
|
Does nothing; placeholder |
|
|
Defines a function |
|
|
Returns a value from a function |
|
|
Creates an anonymous function |
|
|
Defines a class |
|
|
Deletes objects |
|
|
Declares a global variable |
|
|
Declares a non-local variable |
|
|
Starts a try block for exceptions |
|
|
Catches exceptions |
|
|
Executes code regardless of exceptions |
|
|
Raises an exception |
|
|
Asserts a condition |
|
|
Imports modules |
|
|
Imports specific parts of a module |
|
|
Renames a module or variable |
|
|
Simplifies exception handling |
|
|
Declares an asynchronous function |
|
|
Awaits an asynchronous call |
|
|
Returns a generator object |
|
|
Starts a pattern matching block |
|
|
Defines a pattern in match statements |
|
|
Special parser keyword (3.9+) |
|
Let's delve deeper into each keyword, understand its purpose, and see how it fits into Python programming.
False
and True
These are the Boolean values in Python, representing false
and true
respectively.
is_active = True
if is_active:
print("The system is active.")
else:
print("The system is inactive.")
True
.if
statement checks if is_active
is True
.None
Represents the absence of a value or a null
value.
result = None
if result is None:
print("No result available.")
result
is assigned None
.result
is None
.and
: Returns True
if both operands are true.or
: Returns True
if at least one operand is true.not
: Inverts the truth value.a = 10
b = 20
if a > 5 and b > 15:
print("Both conditions are True.")
a > 5
and b > 15
are True.is
Checks if two variables point to the same object.
a = [1, 2, 3]
b = a
print(a is b) # Output: True
b
references the same list as a
.is
checks for object identity.in
Checks if a value is present in a sequence.
fruits = ['apple', 'banana', 'cherry']
if 'banana' in fruits:
print("Banana is in the list.")
banana
' is an element of the fruits
list.Used for conditional branching.
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C")
True
.for
LoopIterates over a sequence.
for i in range(5):
print(i)
while
LoopRepeats as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
break
Exits the nearest enclosing loop.
for i in range(10):
if i == 5:
break
print(i)
continue
Skips the rest of the code inside the loop for the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
pass
Does nothing; acts as a placeholder.
def function():
pass # Function implementation will be added later
def
Defines a function.
def add(a, b):
return a + b
a
and b
.return
Exits a function and returns a value.
def square(x):
return x * x
x
.lambda
Creates an anonymous function.
double = lambda x: x * 2
print(double(5)) # Output: 10
lambda x: x * 2
defines an anonymous function that doubles the input.class
Defines a class.
class Person:
def __init__(self, name):
self.name = name
Person
with an initializer method.del
Deletes objects.
x = 10
del x
x
from the namespace.global
Declares a global variable inside a function.
count = 0
def increment():
global count
count += 1
nonlocal
Declares a non-local variable inside nested functions.
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
print(x) # Output: 10
x
in the outer function from within inner.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.try:
x = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print(f"You entered {x}")
finally:
print("Execution complete.")
ValueError
if conversion fails.else
block runs if no exception occurs.finally
block runs regardless.raise
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return a / b
b
is zero.assert
def square_root(x):
assert x >= 0, "x must be non-negative"
return x ** 0.5
x
is non-negative before proceeding.import
: Imports a module.from
: Imports specific attributes from a module.as
: Renames the module or attribute.import math
print(math.pi)
from math import sqrt
print(sqrt(16))
import numpy as np
math
module.sqrt
function from math
.numpy
and aliases it as np
.with
Simplifies exception handling by encapsulating common preparation and cleanup tasks.
with open('file.txt', 'r') as file:
content = file.read()
async
and await
Used for asynchronous programming.
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())
async
.await
pauses execution until the awaited task is complete.Used in generator functions to return a value and pause execution.
def generator():
for i in range(3):
yield i
for value in generator():
print(value)
generator()
yields values one at a time.for
loop retrieves each value.Introduced in Python 3.10 for structural pattern matching.
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
match
checks the value of status.case
matches specific patterns._
is
a wildcard for any value.if
, else
, for
, while
, etc.def
, class
, lambda
, etc.try
, except
, finally
, raise
, assert
.and
, or
, not
, is
, in
.match
and case
were introduced in Python 3.10 for pattern matching.async
and await
facilitate concurrent execution.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!