Python Keywords

Python keywords are reserved words that have specific meanings and purposes within the Python language. You cannot use them as variable names, function names, or any other identifier. These keywords help define the structure and logic of Python programs.

Here is a list of the most commonly used Python keywords, along with brief descriptions of their functions:

1. False

Represents the boolean value False.

x = False

2. None

Represents the absence of a value or a null value.

x = None

3. True

Represents the boolean value True.

x = True

4. and

Logical operator used to combine conditional statements. Returns True if both operands are True.

x = True and False  # False

5. as

Used to create an alias for a module when importing or for handling exceptions.

import math as m

6. assert

Used for debugging purposes. It tests if a condition is True, and if not, raises an AssertionError.

assert 2 + 2 == 4

7. async

Defines an asynchronous function or coroutine.

async def my_func():
    await some_task()

8. await

Used inside an async function to pause the execution until the awaited coroutine is completed.

await my_func()

9. break

Exits a loop prematurely.

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

10. class

Defines a new user-defined class.

class MyClass:
    pass

11. continue

Skips the rest of the current iteration of a loop and moves to the next iteration.

for i in range(5):
    if i == 2:
        continue

12. def

Defines a new user-defined function.

def my_function():
    pass

13. del

Deletes an object, variable, or element in a list or dictionary.

del x

14. elif

Short for “else if.” It’s used to add more conditions in an if statement.

if x == 1:
    pass
elif x == 2:
    pass

15. else

Specifies a block of code to be executed if the if or elif condition is False.

if x == 1:
    pass
else:
    pass

16. except

Handles exceptions that occur in a try block.

try:
    x = 1 / 0
except ZeroDivisionError:
    pass

17. finally

Specifies a block of code to be executed regardless of whether an exception occurs or not.

try:
    pass
finally:
    pass

18. for

Starts a loop that iterates over a sequence (such as a list, tuple, or string).

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

19. from

Used to import specific parts of a module.

from math import sqrt

20. global

Declares a global variable inside a function.

global x
x = 5

21. if

Executes a block of code if the condition is True.

if x == 1:
    pass

22. import

Imports a module into the current namespace.

import math

23. in

Checks if an element exists within a sequence or iterable.

if 1 in [1, 2, 3]:
    pass

24. is

Checks if two variables point to the same object in memory (compares identities).

x = [1, 2]
y = x
if x is y:
    pass

25. lambda

Creates a small anonymous function.

x = lambda a: a + 10

26. nonlocal

Declares a variable to refer to a variable in the nearest enclosing scope (not global scope).

def outer_func():
    x = 10
    def inner_func():
        nonlocal x
        x = 20

27. not

Logical operator that negates a condition (returns True if the condition is False).

if not x:
    pass

28. or

Logical operator used to combine conditional statements. Returns True if at least one of the operands is True.

x = True or False  # True

29. pass

A null operation used when a statement is syntactically required but no code needs to be executed.

if x:
    pass

30. raise

Raises an exception manually.

raise ValueError("Invalid value")

31. return

Exits a function and returns a value to the caller.

def my_function():
    return 5

32. try

Specifies a block of code to test for errors.

try:
    pass

33. while

Starts a loop that repeats as long as the condition is True.

while x < 5:
    pass

34. with

Simplifies exception handling by automatically managing resources such as file streams.

with open("file.txt", "r") as file:
    data = file.read()

35. yield

Pauses a function and returns a value to the caller, but retains enough state to resume where it left off.

def generator():
    yield 1
    yield 2

36. async and await

Used to define and handle asynchronous code (coroutines). Common in Python’s asynchronous programming to work with tasks like I/O-bound operations.

async def my_async_function():
    await some_task()

Summary of Keywords:

  • Control Flow: if, elif, else, for, while, break, continue, return, yield
  • Exception Handling: try, except, finally, raise, assert
  • Variable Scope: global, nonlocal
  • Logical Operators: and, or, not, is, in
  • Asynchronous: async, await
  • Functions and Classes: def, class, lambda
  • Modules: import, from, as
  • Others: True, False, None, with, del, pass

Each of these keywords is essential to Python’s structure and functionality, helping to build logic, handle errors, control flow, and work with asynchronous tasks.

Leave a Reply 0

Your email address will not be published. Required fields are marked *