Python Keywords

What are keywords

Keywords in Python or any other language are some special reserved words that have a predefined meaning to the Interpreter, and that's why keywords can't be used as an identifier in that language. There are many keywords available in the Python language.

Available Keywords in Python

The predefined words or reserved keywords for python language are given below:

False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

Keyword Explanations

Python True and False keywords

These are used in conditional statements. The keywords are self-explanatory. In Python, True is equivalent to integer 1, and False is equal to integer 0.

			

name=" John Doe" 
age=25 
del age 
print(age)  
# age is no longer exist  
print(name)   

				

Output:

Traceback (most recent call last): File "main.py", line 4, in <module> print(age) NameError: name 'age' is not defined ** Process exited - Return Code: 1 ** Press Enter to exit terminal

Python None keyword

The None keyword represents the None or empty dataType. It is a data type that represents no values or a null value in Python.

			

apple = "Available"
orange = None
def menu(x):
   if x == apple:
       print(apple)
   else:
       print(orange)

menu(apple)
menu(orange)

				

Output:

Available None

Python and, or, not keywords

In Python, these three keywords are used as Logical operators

Operator Operation
and And operator returns the True value if both the operand expressions are True else returns False.
or Returns True if either of the operand expressions is True else returns False.
not Returns the inverted expression result.
			

if 3==3 and 4==5:
   print("True")
else:
   print("False")

if 3==3 or 4==5:
   print("True")
else:
   print("False")

if not(3==3 and 4==5):
   print("True")
else:
   print("False")

				

Output:

False True True

Python as keyword

The as keyword directs Python to load the library to a particular name you specify. With as keyword user is giving a nickname to a complete library Example, we can import the numpy module and make an alias of it with the name np.

			

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)

				

Python assert keyword

The assert keyword is a special statement in the Python language as it raises an AssertionError exception if the statement that follows it evaluates to False. It is used for debugging code. The message string after the comma is considered an error string that will be passed to the AssertionError exception.

			

assert 1==True, "This is the error message"
assert 0==True, "This is the error message"

				

Output:

AssertionError: This is the error message

Python async, await keywords

The async keyword allows a function to run asynchronously. While await keyword instructs the program to pause further execution for a specified amount of time.

			

import asyncio

async def t(i):
   print(f"hello {i} started")
   await asyncio.sleep(4)
   print(f"hello {i} done")

async def main():
   my_task1 = asyncio.create_task(t(1))
   my_task2 = asyncio.create_task(t(2))
   await my_task1
   await my_task2

asyncio.run(main()) 

				

Python break keyword

break keyword in Python is used inside a loop(for, while, etc.) to exit or terminate the loop and bring the execution control outside the loop. break is written inside a loop to bring the execution control outside the loop.

			

for num in range(1,11):
   if num == 7:
       break
   print(num)

				

Output:

1 2 3 4 5 6

Python continue Keyword

continue keyword in Python is used to skip the loc (lines of code) inside the current running loop without breaking it and executing the next iteration of the same loop.

			

for num in range(1,11):
   if num == 6:
       continue
   print(num)

				

Output:

1 2 3 4 5 7 8 9 10

Python class Keyword

The class keyword in Python defines a class. Class is a blueprint of user-defined object for a type. It defines its properties and behavior.

			

class MyClass:
   def __init__(self):
       print("This is MyClass")

my_object = MyClass()

				

Output:

This is MyClass

Python def Keyword

def keyword defines a function in Python.

			

def my_function():
   print("My function executed")

my_function()

				

Output:

My function executed

Python del Keyword

del keyword in Python can delete lists, tuples, integers, dictionaries, etc.

			

my_list = [1,2,3,4]

del my_list[3]

print(my_list)


my_int = 55

del my_int

print(my_int)

				

Output:

[1, 2, 3] NameError: name 'my_int' is not defined.

Python if, else, elif keywords

These keywords are used for decision-making. If the keyword is used after the conditional statement. If the statement turns out to be True then the instructions written in the if block are executed. If the condition turn out to be False, then the instructions inside the else block are executed. name = "John"

			

name = "John"
if name == "John":
   print("If block executed")
else:
   print("else block executed")

				

Output:

If block executed

Python allows writing multiple if statements together by making use of elif keyword. Like this

			

name = "John"
if name == "John":
   print("John")
elif name == "Harry":
   print("Harry")
elif name == "Alexander":
   print("Alexander")
elif name == "Ruskin":
   print("Ruskin")

				

Output:

John

Python except, raise, try keywords

These keywords handle exceptions in the program. The code that can raise to exception is written within the try block, and the program that can handle the exception is written inside the except block.

			

def my_function(num):
   try:
       value = 1/num
   except:
       print('Exception occured')
       return
   return value

print(my_function(10))
print(my_function(0))

				

Output:

0.1 Exception occured None

Since my_function() returns the reciprocal of a number, if 0 is passed to the function it raises an exception, because the reciprocal of 0 is undefined. We can explicitly raise an exception in the program with the raise keyword.

			

if num == 0:
    raise ZeroDivisionError('cannot divide')

				

Python finally keyword

The finally keyword is written within a block of code that will be executed in every situation, and the block of code is independent from the results or execution inside the try except blocks.

			

def my_function(num):
   try:
       value = 1/num
   except:
       print('Exception occured')
       return
   finally:
       {
           print("Finally Block")
       }
   return value

print(my_function(10))
print(my_function(0))

				

Output:

Finally Block 0.1 Exception occured Finally Block None

Also, in the above example, the finally block is always executed.

Python for keyword

The for keyword is used for loop, and it is used to execute a piece of code a given number of times.

			

names = ["John", "Dwayne", "Rocky", "Mitchael"]

for name in names:
   print(name)

				

Output:

John Dwayne Rocky Mitchael

Python from, import keywords

The import keyword in Python includes a module in the code. These modules have pre-coded functionality that can be used in the code for easier execution. The from keyword is used to import only specific parts of the module within the import syntax.

			

from numpy import array

print(array([1,2,3]))

				

In the above code, using from the from… import syntax, This will import only the array functionality from the huge numpy module. Also, while using this syntax we do not need to refer to array as numpy.array. We can write array to build arrays in the program.

Python global keyword

The global keyword is used within a function to declare that the variable used inside this scope is the global variable that was declared previously. By default, if a variable is declared outside the function and then we try to modify that variable inside the function, we will access a local copy of that variable and not the actual variable itself. For example

			

num = 45

def my_func():
   num =10
   print(num)

my_func()

print(num)

				

Output:

10 45

By declaring the global variable inside the function, the original variable can be accessed in the function.

			

num = 45

def new_func():
   global num
   num =10
   print(num)

new_func()

print(num)

				

Output:

10 10

Python in keyword

The in keyword is used for a membership test of a literal or variable in a sequence type object. That means it checks whether the literal or variable is present inside the sequence object or not. If the variable is present inside the object, then this keyword will return True else, it will return False.

			

num = 1
print(num in [1,2,3,4])

				

Output:

True

Python is keyword

The is keyword is used to perform an Identity test of two literals or variables. That means it checks whether the two literals or variables are referencing the same memory location or not(unlike the == operator, which checks if the value is equal or not). If the variables are referencing the same memory location, then this keyword will return True else it will return False.

			

nums = [1,2,3,4]

another_nums = nums

print(nums is [1,2,3,4])
print(nums is another_nums)

				

Output:

False True

Python lambda keyword

The lambda keyword is used for creating inline functions without any name. These functions do not have nay return statement. It is a quick method to create small functions.

			

squares = lambda x: x*x
for num in range(1,5):
   print(squares(num))

				

Output:

1 4 9 25

Python nonlocal keyword

The nonlocal keyword works similarly to the global keyword. It is also used within a function to declare that the variable we are using in this scope is the nonlocal variable declared earlier.

			

def outer_function():
   var = "local"

   def inner_function():
       nonlocal var
       var = "nonlocal"
       print("inner:", var)

   inner_function()
   print("outer:", var)
outer_function()

				

Output:

inner: nonlocal outer: nonlocal

Python pass keyword

The pass keyword works as a placeholder, and its responsibility is to create a body for an empty function or class.

			

class newCLass:
   pass

def new_func():
   pass

				

Python return keyword

The return keyword is used to return the output of a function and to end the execution of the function it return the specified result. It can also be kept empty. Meaning we can return None.

			

def new_func(num):
   return num+2

print(new_func(5))

				

Output:

7

Python while

The while keyword is used to implement the while loop, the loop executes a piece of code multiple times until a given condition is True. If the condition turns out to be False, the loop gets terminated.

			

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

				

Output:

0 1 2 3 4

Python yield keyword

The yield keyword is used to return a generator from a function. Generators generate a single value at a time.

			

def generator():
   for num in range(4):
       yield num**num

my_gen = generator()
for g in my_gen:
   print(g)

				

Output:

1 1 4 27

Python with keyword

The with keyword is used with try…. except keywords similar to the finally keyword. It is used to free up resources while accessing them, even if the code raises an exception. For example, with is used to automatically destroy the file object even if an exception occurs while accessing the file.

			

with open('my_file.txt', 'w') as file1:
   file1.write('Contents of file1')