In this post, we will learn about python keywords and their uses with examples.

So let’s start from the very basics..

What are Keywords in python

In Python, a keyword is a word that has a special meaning in the Python language. Keywords are used to define the syntax and structure of the Python language, and they cannot be used as variables or identifiers in your code.

List of Python Keywords

There are a total of 35 keywords in Python. Here is a list of all the Python keywords:

KeywordDescription
andUsed to combine two Boolean expressions. Returns True if both expressions are True, and False otherwise.
asUsed to import a module or package and give it an alias.
assertUsed to test a condition and raise an exception if the condition is False.
asyncUsed to define an asynchronous function.
awaitUsed to wait for the completion of an asynchronous function.
breakUsed to exit a loop prematurely.
classUsed to define a new class.
continueUsed to skip the rest of the current iteration of a loop and move on to the next iteration.
defUsed to define a new function.
delUsed to delete an object or an element from a list.
elifUsed in an if statement to specify additional conditions to be tested if the previous conditions are False.
elseUsed in an if statement to specify a block of code to be executed if all the previous conditions are False.
exceptUsed in a try statement to specify a block of code to be executed if an exception is raised.
FalseRepresents the Boolean value False.
finallyUsed in a try statement to specify a block of code that will always be executed, regardless of whether an exception is raised.
forUsed to create a loop that iterates over a sequence of elements.
fromUsed to import specific modules or symbols from a package or module.
globalUsed to declare a variable as global.
ifUsed to specify a block of code to be executed if a condition is True.
importUsed to import a module or package.
inUsed to test if an element is contained in a sequence.
isUsed to test if two objects are equal.
lambdaUsed to create a small anonymous function.
NoneRepresents the null value.
nonlocalUsed to declare a variable as nonlocal.
notUsed to negate a Boolean expression.
orUsed to combine two Boolean expressions. Returns True if either expression is True, and False otherwise.
passUsed as a placeholder for a block of code that does nothing.
raiseUsed to raise an exception.
returnUsed to exit a function and return a value.
TrueRepresents the Boolean value True.
tryUsed to specify a block of code to be tested for exceptions.
whileUsed to create a loop that continues as long as a condition is True.
withUsed to create a context manager that manages the execution of a block of code.
yieldUsed in a function to return a value and pause the function’s execution. The function can be resumed later from where it left off.

It is important to note that Python is a case-sensitive language so “True” and “true” are not the same keyword.

You should avoid using these keywords as variable names or function names in your code to avoid any syntax errors or unexpected behavior. Instead, you should use descriptive names for your variables and functions that accurately reflect their purpose in your code.

All the Python Keywords with Example

Here is a brief explanation of each Python keyword, along with an example of how it can be used in your code:

and: Used to combine two Boolean expressions. Returns True if both expressions are True, otherwise returns False.

#Example
x = 3
y = 5
if x > 0 and y > 0:
    print("Both x and y are positive.")

as: Used to import a module or package and give it an alias.

#Example
import numpy as np

assert: Used to test a condition and raise an exception if the condition is False.

#Example
x = -3
assert x > 0, "x must be positive."

async: Used to define an asynchronous function.

#Example
async def fetch_data():
    # Asynchronous code here
    pass

await: Used to wait for the completion of an asynchronous function.

async def main():
    data = await fetch_data()
    # Do something with the data
    pass

break: Used to exit a loop prematurely.

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

class: Used to define a new class.

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

continue: Used to skip the rest of the current iteration of a loop and move on to the next iteration.

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

def: Used to define a new function.

def greet(name):
    print("Hello, " + name + "!")

del: Used to delete an object or an element from a list.

x = 10
del x

elif: Used in an if statement to specify additional conditions to be tested if the previous conditions are False.

x = -3
if x > 0:
    print("x is positive.")
elif x < 0:
    print("x is negative.")
else:
    print("x is zero.")

else: Used in an if statement to specify a block of code to be executed if all the previous conditions are False.

x = -5
if x > 0:
    print("x is positive.")
else:
    print("x is not positive.")

except: Used in a try statement to specify a block of code to be executed if an exception is raised.

try:
    # Code that might raise an exception
    pass
except SomeException:
    # Code to handle the exception
    pass

False: Represents the Boolean value False.

x = False
if x == False:
    print("x is False.")

finally: Used in a try statement to specify a block of code that will always be executed, regardless of whether an exception is raised.

try:
    # Code that might raise an exception
    pass
except SomeException:
    # Code to handle the exception
    pass
finally:
    # Code that will always be executed
    pass

for: Used to create a loop that iterates over a sequence of elements.

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

from: Used to import specific modules or symbols from a package or module.

from math import pi

global: Used to declare a variable as global.

x = 10
def increment():
    global x
    x += 1

print(X)

if: Used to specify a block of code to be executed if a condition is True.

x = 9
if x > 0:
    print("x is positive.")

import: Used to import a module or package.

import math

in: Used to test if an element is contained in a sequence.

my_list = [1,2,3,4,5,6,7]
x = 5
if x in my_list:
    print("x is in the list.")

is: Used to test if two objects are equal.

x = None
if x is None:
    print("x is None.")

lambda: Used to create a small anonymous function.

double = lambda x: x * 2

None: Represents the null value.

x = None

nonlocal: Used to declare a variable as nonlocal.

def outer():
    x = 10
    def inner():
        nonlocal x
        x += 1
    inner()
    return x

not: Used to negate a Boolean expression.

x = False
if not x:
    print("x is False.")

or: Used to combine two Boolean expressions. Returns True if either expression is True, and False otherwise.

x = 3
y = -5
if x > 0 or y > 0:
    print("Either x or y, or both, are positive.")

pass: Used as a placeholder for a block of code that does nothing.

def do_nothing():
    pass

raise: Used to raise an exception.

raise ValueError("Invalid value.")

return: Used to exit a function and return a value.

def double(x):
    return x * 2

True: Represents the Boolean value True.

x = True
if x == True:
    print("x is True.")

try: Used to specify a block of code to be tested for exceptions.

try:
    # Code that might raise an exception
    pass
except SomeException:
    # Code to handle the exception
    pass

while: Used to create a loop that continues as long as a condition is True.

x = 10
while x > 0:
    print(x)
    x -= 1

with: Used to create a context manager that manages the execution of a block of code.

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

yield: Used in a function to return a value and pause the function’s execution. The function can be resumed later from where it left off.

def infinite_sequence():
    i = 0
    while True:
        yield i
        i += 1
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment