01 logo

7 Programs to Understand All 35 Keyword In Python

All the keywords are explained in detail with code

By Swathi ArunPublished 3 years ago 7 min read
Like
7 Programs to Understand All 35 Keyword In Python
Photo by James Harrison on Unsplash

Keywords are the basics of Python programming that everyone must know. These are the reserved words in Python. Some keywords are interesting and yet rarely used. That is why it is essential to take into account how many keywords are there and their functionality. Each keyword is unique and has a different function. In this article, I will try to explain all the 35 Python keywords in detail.

1. async and await:

All the programs by default run synchronously. With these keywords, you can make a program run asynchronously. This can help with the performance of the program when you parallelize input and output operations.

A program to understand asyncio by creating 3 tasks using asyncio function and await.

import asyncio

async def function(i):

print(f"Hello, function {i} started")

await asyncio.sleep(4)

print(f"Hello function {i} has been completed")

async def main():

task1 = asyncio.create_task(function(1))

await asyncio.sleep(2)

task2 = asyncio.create_task(function(2))

await asyncio.sleep(2)

task3 = asyncio.create_task(function(3))

await task1

await task2

await task3

asyncio.run(main())

Output:

Image by Author

Note:

  • await and async are also known as promise keywords. When the keyword async is used before a function, it makes that function pause your code until the promise fulfills.
  • asyncio.run() and asyncio.create_task() are functions used in the code to run the program and create a task.
  • Also notice that function 1 is completed even before function 3 is started because of the wait time.

2. True, False, and, or, not:

True and False is a value of class type boolean(bool). And, Not and Or are created to represent the logical operations in Python. I have tried to use those with logical operators and, or and not in this program.

A Program by using True or False with logical operators(And, Or, Not)

print("AND operation between True and False Keyword is")

print(str(True and False))

print("-------------------------------------------")

if (True or False):

print("OR operation of True and False is True")

print("-------------------------------------------")

a =not (True)

print("Not of True is",a)

Output:

Image by Author

Note:

  • and -The first operation is the and operation, the result will be true only if both are true. That is why is the output is false
  • or -In or operation, if one of them is true then the output will be true
  • not -The last one is the not operation, the inverse of true is false

3. break, continue, pass, while, for, in:

Iteration is the process of repeating a code while the given condition is true. Keywords break, continue and pass are unique. If you see them working in a single program it is very easy to understand the working of those keywords.

A program with to understand the working of pass continue and break

for count in range(1,10):

while (count< 3):

print(f"This is for the count {count}")

count+=count

if count == 3:

pass

print(f"This is pass block for count {count}")

print(f"This is also the pass block")

elif count ==4:

continue

print("This statement will not be executed")

else:

break

print("This statement will not be executed")

print(count)

Output:

Image by Author

Note:

  • for, in -When execution of code repetitively for a specific number of times with range function.
  • while — while loop executes until the condition is true. In this example, the code executes for a count of less than 3.
  • pass -This is a null operator, when the code executes a pass statement it executes all the code in the pass block. In the example check count 3 will enter the pass block.
  • continue -When the code reaches the continue, it rejects all the remaining statements and moves control back to the loop. In the example notice that print statement is not executed
  • break — This statement stops the execution of the complete loop. In the example, despite being for range from 1 to 10, execution stops at 5, which is why the output is count 5.

4.def,from,import,as, yield:

In this, we will try to define a function, and instead of return, we use yield. And import square root function from a package known as math.

A program to demonstrate the use of yield keyword

from math import sqrt as s

def squareroot(square):

for i in square:

a=s(int(i))

yield a

square = ["4","9","16"]

generator =list(squareroot(square))

print(generator)

Output:

Image by Author

Note:

  • from, import, as -In the code, you import a square root function from a math package in an alias using as.
  • def -This keyword is used to define a function. In the program, a function known as square root is created.
  • yield -When there is a yield statement instead of a return, yield acts as a generator. The output generated is a square root of all the elements in the list.

5.class,none,is:

Class is a keyword that is essentially used with object-oriented programming language. The is keyword is used to check if two variables are equal and if two are the same objects. If they are the same objects then it will return true as output.

A program to check if two variables and two different objects are the same

class age:

age = None

def __init__(self, age):

self.age = age

a = 10

b = a

person1 = age(20)

person2 = age(20)

print(a is b)

print(person1 is person2)

print("age of Person1 : {}".format(person1.age))

print("age of Person2 : {}".format(person2.age))

Output:

Image by Author

Note:

  • is -Notice while checking with two variables with is the keyword. The output is true because two variables refer to the same object.
  • The next output is false because we have created two different objects that cannot be equal using class.

6. try, except, finally, raise, del:

The exception handling mechanism uses some special keywords like try, except, finally. The del keyword deletes objects in the python program. After deleting with del the output will have an error message.

A program to raise a zero division error and deleting an object

a = 10

b = 0

try:

c = a + b

print(c)

d= a/b

except ZeroDivisionError:

raise

finally:

print("This is the finally after try and except block")

del c

print(c)

Output:

Image by Author

Note:

  • try -This keyword is used for a block when there is a potential exception in the code.
  • except -With the except block you can handle any error occurring in the try block.
  • finally -This block will get executed after the try and the except block.
  • del -The del keyword is used to delete any object in the python program.

7. with, return, non-local, if, else, elif, global, assert:

In this program, we try to check for conditions. For different condition different operation takes place. The assert keyword helps to the program are for condition, if not it will terminate the program.

A program using if loop to check the different conditions and perform different operations

x = int(input("enter "))

assert x>0 and x<15, 'Number should be greater than 0 and less than 15'

def func1():

global y

y = "Program"

x = "Python"

def func2():

nonlocal x

x = "language"

func2()

return x

if x > 10:

print(func1())

elif x<5:

print(func1())

print(y)

else:

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

f.write('Hi there!')

print("Write details in file")

Output:

Image by Author

Note:

  • if, elif, else -These keywords are most commonly used. If and elif check for a condition if it is true then a block is executed. After which if the conditions are not true then the else block is executed.
  • assert -The assert keyword accepts a boolean expression. If it is false then the program will be terminated.
  • nonlocal — Use nonlocal keywords to declare variables when working with nested functions.
  • global — This keyword is used to declare variables at the top scope of the program. This variable can be accessed from other scopes of the program.
  • with — This keyword is majorly used to manage the external resources for the program.

This article was originally published on Medium. Leave a heart or a tip as encourage, if you like the article. Thank you

list
Like

About the Creator

Swathi Arun

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2024 Creatd, Inc. All Rights Reserved.