Keywords in Python: A Brief Introduction

Sep 13, 2020
8 min read

Python is a dynamic and evolving language. There's a new version always in development that comes with some improvements. Python comes in various versions such as 1.X, 2.X and 3.X series.

As for Python keywords, they are reserved words which means they can’t be changed or used as a variable name, function name, dictionary name or as any other identifier.

Let’s jump to keywords that are supported by Python 2.X and Python 3.X.

Though there are several keywords that are similar in both functions, some keywords are specific to Python 2.X Python 3.X.

Keywords supported by Python 2.X

Here is the table of keywords supported by Python 2.X.

Keywords supported by Python 3.X

Here's a table of keywords supported by Python 3.X.

Function of keywords

Let's discuss when and how these keywords are uses in programming.

Value keywords

The False keyword

Python offers something called the comparison operator which identifies "False" keywords, this occurs when all the condition don’t satisfy. The comparison operator also represents the "truth value" in Python which is the same as zero (0).

>>> x=5
>>> y=10
>>> x>y
keyword False

The True keyword

This one is a Boolean value much like the False keyword. The result derives from comparison operation which is same as one (1).

>>> x=5
>>> y=10
>>> x<y
keyword True

The None keyword

The keyword None basically represents the null variable or the object. It is also the default value that the function returns in case there isn't a return statement.

>>> def test_function(): 
>>>    print('Hello World')
>>> x= test_function()
>>> print(x) 

Hello World
keyword None

Operands keywords

The And keyword

The keyword And checks whether the left and right operands in boolean expression are True or not. If both satisfy the condition then it must return True otherwise it is False.

>>> True and False
keyword and

The Not keyword

This keyword primarily inverts the result of conditional statement. First it finds the Boolean value i-e True or False , then it returns the result after flipping.

>>> not False
keyword not

The Or keyword

The logical or operation returns True when at least one operand satisfies the given condition.

>>> True or False
keyword or

The Is keyword

This keyword Is is used to check the identity of the object. The result doesn’t turn true for equal objects but only for exact objects in memory.

>>> True is True
keyword is

The In keyword

It is membership operator. It checks if any specific member is the part of the container or not. The result is generally True or False.

>>> list=['Harry','John','Alice']
>>> 'Harry' in list
keyword in

Control flow keywords

The If keyword

For conditional statements we use keyword If which is mostly executed only when the condition If is true.

The Elif keyword

This keyword is only used when we have an If statement. It is basically "Else If". When the condition of If statement is False it continues with Elif block. We may have multiple Elif blocks in the code.

The Else keyword

If the set condition for If and Elif blocks are False then the body of Else will be executed.

>>> def if_elif_else(x):
>>>    if x < 0:
>>>       print('x is negative')
>>>    elif x == 0:
>>>       print('x is zero')
>>>    else:
>>>       print('x is positive')
>>> if_elif_else(1)
>>> if_elif_else(-1)
>>> if_elif_else(0)

x is positive
x is negative
x is zero
keywords if, elif and else

Iteration keywords

The for keyword

In Python, we define loop by the keyword For. It iterates over items in a variable, list, tuple or dictionary.

>>> fruits = ["apple","banana","mango"]
>>> for x in fruits:
>>>   print(x)

keyword for

The While keyword

In python, while loop uses the keyword While. The loop continues to run the block till the expression that follows the While keyword is true.

The Break keyword

We can use keyword Break in both for and while loop. It stops the execution of the current loop and moves to the next section which is immediately below the loop.

The Continue keyword

Like the keyword Break, Continue also works for both loops i.e For loop and While loop.

It basically skips the current iteration and moves to the next one.

>>> i=0
>>> while True:
>>>    i += 1
>>>    if i>=5 and i<= 10:
>>>       continue # skip the next part
>>>    elif i == 15:
>>>       break #stop the loop
>>>     print(i)
Keywords while,continue and break 

Structure keywords

The Class keyword

Python is Object Oriented Programming (OOP), a class which is used for describing one or more objects. This keyword helps to create a user defined class.

>>> class Person:
>>>   name ="Hannah"
>>>   age = 12
keyword class

The Def keyword

It helps to define user-defined function or method of a class. The purpose of using functions is to organise our set of instructions.

>>> def my_function():
>>>   print("This is my function")
>>> my_function()

This is my function
keyword def

The With keyword

In Python context managers are very supportive which can be used with the help of With keyword. The basic example is to with I/O files. It opens the specific file, manipulates, and closes it.

>>> with open('file_path','w') as file:
>>>    file.write('Hello World')
keyword with

The Pass keyword

The pass statement (equivalent to null statement) in python does nothing. We use Pass when we need a statement but don’t want to run any code. Following are the few useful examples of using keyword pass.

>>> def my_function():
>>>     pass
>>> class My_Class:
>>>     pass
>>> if True:
>>>     pass
keyword pass

The Lambda keyword

This keyword is used to create anonymous function (with no name). It has only one statement and no return statement.

>>> square =lambda x:x**2
>>> for item in range(5,10):
>>>    print(square(item))
keyword lambda

Returning keywords

The return keyword

The Return keyword is used only inside the body of a function (defined by using the keyword def).Whenever keyword return comes, the programme will exit the function and nothing executes after it.

>>> def factorial(n):
>>>     if n==1:
>>>         return 1
>>>     else:
>>>         return n * factorial(n-1)
>>> factorial(4)

keyword return

The Yield keyword

The Yield is similar to the Return keyword in the function. Just as keyword Return returns the result to the caller, the Yield returns a generator.

>>> def function_name():
>>>     yield "H"
>>>     yield "E"
>>>     yield "L"
>>>     yield "L"
>>>     yield "O"
>>> check = function_name()
>>> for i in check:
>>>     print(i)

keyword yield

Import Keywords

The Import keyword

When we need to import other modules in our programme, we use the keyword. Import.

The From keyword

It is used to import some specific variable, class or function from the module.

The As keyword

This keyword helps us define another name for a module which mostly is imported.

In this case, we are importing the module factorial from Maths which can also be called fac.

>>> from math import factorial as fac
>>> num = 5 
>>> # printing factorial 
>>> print("factorial of " , num , "is =" , fac(num))

factorial of 5 is = 120
keywords from, import and as

Exceptional handling keywords

The Try keyword

The errors which programmer can except during run time written in try block.

The Except keyword

The keyword Except handles exception in the programme. This function is executed when error occurs in the Try block. We can use more Except block with one try block.

The Finally keyword

Whatever is in the Final block gets executed regardless an error occurs or not in the try block.

>>> try:
>>>    x = 3/0
>>>    print(x)
>>> except:
>>>    print("Something went wrong")
>>> else:
>>>    print("Nothing went wrong")
>>> finally:
>>>    print("Bye")

Something went wrong
keywords try, except and finally

The Raise keyword

This keyword is used for raising our own errors in the programme.

>>> if x<3:
>>>   raise Exception("Write number greater than three")
keyword raise

The Assert keyword

If we are to confirm certain statements - that is to discover if it is true or not, then we use keyword Assert.

This keyword is used to insert debugging assertion in our programs. If the assertion becomes true it will run the programme otherwise it raises an Assertion Error.

>>> val = 10
>>> assert val > 100

AssertionError                            Traceback (most recent call last)
<ipython-input-3-b9ae8230c2be> in <module>()
      1 val = 10
----> 2 assert val > 100

keyword assert

Variable handling keywords

The Del keyword

Keyword Del is used to delete reference of objects in the programme. Commonly, it is used to remove indexes from list or a dictionary.

>>> names = ["John","Tom"]
>>> del names[1]
>>> print(names)

keyword del

The Global keyword

The Global keyword reads and modifies the global variable. It also pulls the variable from global scope into the function.

>>> x = "global"
>>> def function():
>>>     global x
>>>     x = x *2
>>>     print(x)
>>> function()

global global
keyword global

The Nonlocal keyword

When working with the nested function, the variable which is defined in the outer function is not local to the inner function. So we can’t modify it without using the keyword nonlocal.

>>> def outer_function():
>>>     x = "local"
>>>     def inner_function():
>>>         nonlocal x
>>>         x = "nonlocal"
>>>         print("inner:",x)
>>>     inner_function()
>>>     print("outer:",x)
>>> outer_function()

inner: nonlocal
outer: nonlocal
keyword nonlocal

Keywords that become built_in function in 3.X series

The Exec keyword

This keyword executed the python code as a string.

>>> exec "x = 3* 7"
>>> x == 21

keyword exec

The print keyword

This keyword is used to print anything to console.

>>> print "That's all about keywords.Hope you like it"

That's all about keywords.Hope you like it
keyword print


In this tutorial we covered all the keywords supported by python 2.X and 3.X series and their uses. Keywords are like the building blocks in the game of python programming. Without using them, it’s not possible for us to write any code. All keywords have their own specific function. To understand and execute the code, these keywords are used by python interpreter.