Python Keywords with Examples

In this Python article, we will discuss the python keywords by implementing them with the example.

Keywords are the pre-defined word having special meaning to the language compiler. These keywords can not be used for anything other than that special purpose.

andasassert
breakclasscontinue
elifdeldef
elseexceptFalse
finallyforfrom
globalifimport
lambdaisin
Nonenonlocalnot
orpassraise
returnTruetry
whilewithyield
__peg_parser__awaitasync
Python Keyword

Let’s see how we can use these Keywords in Python

1. and, or, not, True, False, is

and, or, not are logical operators which after comparing the operands return a boolean value i.e. either True or False.

is keyword is an identity operator which is used to check if two values reside in the same memory location or not.

# and returns true if both the operands are true else it returns false
print(True and False)

# or returns true if any of the operands are true else it returns false
print(True or False)

# not returns the opposite True--> False   False--> True
print(not(True))

print(type(2) is int)
Output
False
True
False
True

2. if, elif, else, for, in

if, elif, else are conditional statements that choose the set of statements for execution, depending on the expression’s return value.

for is used to perform a set of instructions repeatedly until a certain condition is fulfilled.

in checks if the element is present or not in the list, tuple, or in a particular range, etc.

for i in range(10):
    if i % 2 == 0:  # true is number is divisible by 2
        print(i, "is a multiple of 2")
    elif i % 3 == 0:  # true is number is divisible by 2
        print(i, "is a multiple of 3")
    else:  # true is number is not divissiblee by 2 nor by 3
        print(i, "is not a multiple of either 2 or 3")
Output
0 is a multiple of 2
1 is not a multiple of either 2 or 3
2 is a multiple of 2
3 is a multiple of 3
4 is a multiple of 2
5 is not a multiple of either 2 or 3
6 is a multiple of 2
7 is not a multiple of either 2 or 3
8 is a multiple of 2
9 is a multiple of 3

3. while, pass, break, continue

while loop iterates until a condition is true.

break statement enables a program to skip over a part of the code by forcing the termination of a loop.

continue statement also skip over a part of the code but instead of forcing the termination of the loop, it forces the next iteration of the loop to take place and skips the current one.

pass statement does nothing. The interpreter does not ignore this statement but since it is a null statement there is no output. So when we don’t want to do anything, or we want to implement a method in the future we use pass statement, otherwise we will get an error.

count = 1
while True:
    if count % 2 == 0:  # only increment if multiple of 2
        count += 1
        continue
    elif count % 3 == 0:  # if count is a multiple of 3 then don't do anything
        pass
    else:
        print(count)

    if count > 10:  # if count is greater than 10 break the loop
        break
    else:
        count += 1
Output
1
5
7
11

4. from, import, as

import is used to use an external source file or module in our current source file.

Whenever we want to import only a specific function from a module we use from

as keyword is used to create an alias or you can say another name .

Syntax : from module_name import function/module name

For learning more about from and import, check the python article on modules.

from datetime import datetime as dt
print(dt.now())
Output
2021-02-17 18:57:51.183834

5. try, except, finally, raise

If inside the try block we will get an error then it will directly be caught by the except block. As soon as we get the error nothing will be executed after that line and the compiler will directly go to the except block.

Finally block always gets compiled, it does not matter if try throws an error or not.

In the below example the try block will throw a ZeroDivisionError and except will catch that.

raise keyword is used to throw an exception intentionally.

try:
    print("working inside try block")
    l = 20 / 0
    print("This line will not print")

except:
    print("Caught the exception")


finally:
    print("It Always print with or without error")

if True:
    raise Exception("Raising an exception")
Output
working inside try block
Caught the exception
It Always print with or without error
Traceback (most recent call last):
File "c:\Users\parih\Desktop\testing.py", line 14, in <module>
raise Exception("Raising an exception")
Exception: Raising an exception

6. def, return, yield, None

def keyword is used to define a function in python. Functions serve two main purposes. The first is to encapsulate a code block and give a meaningful descriptive name to it so that it makes the code clean and easy to read. And the second use is reusability i.e. whenever we need a code, again and again, we use a function instead of writing the code multiple times.

return is used to return some value from the function .

yield is the same as a return but instead of returning just the value, it returns a generator.

None keyword is as no value. None is its own data type it is not equal to 0 or False

def test_for_return():
    return "Codingeek"


def test_for_yield():
    yield "Codingeek"


def test_for_none():
    return None


print("return value : ", test_for_return())
print("return type : ", type(test_for_return()))
print("yield keyword : ", test_for_yield())
print("yield type : ", type(test_for_yield()))
print("None Keyword : ", test_for_none())
print("None type : ", type(test_for_none()))
Output
return value :  Codingeek
return type :  <class 'str'>
yield keyword :  <generator object test_for_yield at 0x000001FA45B0AC10>
yield type :  <class 'generator'>
None Keyword :  None
None type :  <class 'NoneType'>

7. assert

assert keyword is mainly used in testing, if the input condition returns true then it does not do anything otherwise it will throw an AssertionError.

assert 10 % 2 == 0, "Not Divisible by 2"
b = 0
assert b != 0, "ZeroDivisionError"
print(20 / b)
Output
Traceback (most recent call last):
File "c:\Users\parih\Desktop\testing.py", line 3, in <module>
assert b!=0,"ZeroDivisionError"
AssertionError: ZeroDivisionError

8. class, del

Python Classes are a way to bind attributes and methods, simply we can say the class is used to bind related variables and function together in a logical entity that can be instantiated and used repeatedly in the code. Classes are basically the blueprint of the object and the instantiated value is known as an Object.

Read More: Classes and Objects

In python we define a class using class keyword.

The del keyword is used to delete an object but everything in python is an object so we using del we can delete anything like variables, list, tuple, classes etc.

class Dialogue:
    name = "Codingeek"

    def say(self):
        print("It's a beautiful day to save lives")


x = Dialogue()
print(x.name)
x.say()
print(Dialogue)
del Dialogue
print(Dialogue)
Output
Codingeek
It's a beautiful day to save lives
<class '__main__.Dialogue'>
Traceback (most recent call last):
File "c:\Users\parih\Desktop\testing.py", line 11, in <module>
print(Dialogue)
NameError: name 'Dialogue' is not defined

9. global, nonlocal

global keyword in Python is used to create a global variable from the no-scope area, for example: inside a function, inside a loop, etc.

the non-local keyword is similar to a global keyword but it is mostly used in the nested function so that the variable modification inside the nested function does not get destroyed in the outer function.

def func1():
    x = "Website"

    def func2():
        nonlocal x
        x = "Codingeek"

    def func3():
        x = "Working"
        global y
        y = "It's global"

    func2()
    func3()
    return x


print(func1())
print(y)
Output
Codingeek
It's global

10. lambda

lambda keyword is used to create a small function, it can take any number of arguments but can have only one expression.

func = lambda x, y, z, l: (x + y + z) * l
print(func(1, 2, 5, 5)) # (1 + 2 + 5) * 5
Output
40

11. with

with keyword in Python is basically used in file handling and simplifies the exception handling because it does the clean-up task after the processing is completed. For example, it automatically closes the file once the with block is executed completely.

with open('output.txt', 'w') as f:
    f.write('Codingeek')

12. await, async,__peg_parser__

await keywords suspend the execution of coroutine on an awaitable object. It can only be used inside a coroutine function.

To define a function coroutine we use the async keyword. Functions defined with “async def” syntax are always coroutine functions, even if they do not contain “await” or “async” keywords.

The async is similar to synchronized keyword in java.

For example:

async def func(param1, param2):
    do_stuff()
    await some_coroutine()

__peg_parser is an Easter egg. It is a new keyword in Python 3.9. The __new_parser__ was renamed to __peg_parser__ recently.

help> __peg_parser__
no documentation found for '__peg_parser__'

>>> __peg_parser__
SyntaxError: You found it!

13. Conclusion

In this article, we discussed all Python keywords and how to implement them in python.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index