×

Keywords in Python

Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name, or any other identifier. The following identifiers are used as reserved words, or keywords of python, and cannot be used as ordinary identifiers.

We can get the list of keywords present in the python using keyword module.

import keyword
print(keyword.kwlist)

To check whether a keyword is valid or not we can use keyword.iskeyword() and pass the word as a string.

print(keyword.iskeyword("def"))
True
Table of Contents

The list of keywords is shown below:-

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

True, False and None

True and False are the boolean values and are used to compare the result of expression evaluations. True and False are most often used in conditional statements.

var = True
if var == True:
	print("hello")

hello

None is a constant that has no value and has its own NoneType data type. None has no value and is not a zero value or is not an empty string or a false value

None == False  -> False
None == 0      -> False
None == ""     -> False

None has different applications and among them, we can use it to assign a new value to a variable by checking if it’s a none or, also assigns none to a variable to erase the contents of it.

var_1 = None
if var_1 == None:
    var_1 = "python"
print(var_1)

python

None is also frequently used to represent the absence of the value, as when default arguments are not passed to a function. In the below example, even if we don’t pass arg_2 value while calling the function, the code is executed without throwing any error.

def func(arg_1, arg_2 = None):
    print(arg_1)
func(5)

as

as is known as alias keyword and is useful when we import any module or file and use it with an alias name.

from bs4 import BeautifulSoup as BS

and, or, not

and, or, not are used as logical operators and they return True or False based on the values of the operands in the expression.

  • and returns True only if both operands are of True value or else it returns false
  • or returns False if both operands are False or else returns True every time
  • not is a complement operators that returns opposite of the value that we pass
True and False -> False
True or False  -> True
True and True  -> True
not True       -> False

assert

assert is a keyword that is used for debugging. we can use a condition to evaluate the expression if it is True or False. If the expression is True then the program executes correctly or else an assertion error will be raised.

var_1 = "python"
assert "p" in var_1

var_2 = 5
assert var_2 < 3

AssertionError

break, continue

break and continue keywords are used in iterations. When we implement a loop it iterates till the condition evaluates to True. We can implement a break and continue to manipulate the iteration.

The main function of break is to stop the iteration and exit the loop. Consider a situation if there is a necessity of terminating the loop if the required state is achieved then a break statement can be implemented.

var = "python"
list = []
for i in var:
    if len(list)>=3:
        break
    list+=[i] 
print(list)

# Output
['p', 'y', 't']

Similarly, continue can be used to pass the control to the next iteration, without causing any interruption to the control flow. The statements that are next to continue are not executed in that particular iteration.

var = "python"
list = []
for i in var:
    if i == "h":
        continue
    list+=[i] 
print(list)

# Output
['p', 'y', 't', 'o', 'n']

async and await

async and await belong to asyncio class and are used for performing asynchronous programming. This comes needy when there is a requirement of executing another task while waiting for the completion of the current task.

This is not a multi-threading concept rather it’s a concept of asynchronous programming. Using an async keyword allows a task to be considered for asynchronous programming and await keyword helps to wait till a particular task is completed.

In the below example func_1 is executed and when it sleeps for 3 seconds in this free time func_2 is executed. Also, the await keyword waits for that particular line of code to be completely executed.

import asyncio
async def func_1():
    task = asyncio.create_task(func_2())
    print("A")
    await asyncio.sleep(3)
    print("B")

async def func_2():
    print(1)
    print(2)
asyncio.run(func_1())

# Output
A
1
2
B

Class

class is a code template for creating objects. In python, a class is created by the keyword class. Classes contain data and functions which is the concept of Object-Oriented Programming ( OOPS ).

class A():
    def func_1():
        ....
    def func_2():
        ....

def

In Python, defining the function works as follows. def is the keyword for defining a function. The function name is followed by a parameter(s) in (). The colon: signals the start of the function body, which is marked by an indentation.

def func_1():
    ....
    ....

def func_2():
    ....
    ....

del

Everything in Python is an object. del is used to remove or delete an object. Once the object is deleted only the reference is deleted and the memory remains the same if there are any other references to it. If there are no references then the memory is also deleted.

a = 5
del a
print(a)

NameError: name 'a' is not defined

if, else, elif

if, else are used as conditional statements. Based on the evaluation of the expression these conditional statements are executed.

  • if the If conidtion is True then else is not executed
  • if the If conidtion is False then else gets executed

Apart from if and else, there is one more clause known as else-if( elif ). Python will check for the condition in the If clause and if it returns False then the python checks for the true condition in the elif clause.

var = "python"
if var == "hello":
    print("if got executed")
elif var == "python":
    print("elif got executed")
else:
    print("else got executed")

# Output
elif got executed

try, except, raise

try and except blocks are used to handle the errors that might be caused due to logical or syntactical errors. If the code in try block throws an error then it is efficiently handled by the except block. Multiple declarations of except block make the program handle the exception efficiently.

def div(num):
    try:
        result = 1/num
    except:
        print('Exception')

div(0)

There are numerous exceptions such as ZeroDivisionError, ArithmeticException, BaseException, BufferError, etc.,

raise is used for raising the exception if there are any errors or something we might not be able to handle.

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

finally

finally is used along with try-except blocks and gets executed independent of try and except block statements. Even if the exception is handling or not does not matter in finally block, it will be executed.

def div(num):
    try:
        result = 1/num
    except:
        print('Exception')
    finally:
        print("got executed")
div(0)

for

for keyword is used to implement for loop on a sequence. Every time the loop iterates, we can store the values of the sequence and perform operations.

This for loop keeps getting executed for the number of items in the sequence and this sequence can be list, tuple, or string, etc.,

for i in "python":
    print(i)

While

While is also a loop that keeps on iterating multiple times as long as the condition is evaluated to True.

Unlike for loop, the while loop does not require any sequence or an iterator. The only thing we need to pass is a condition with a value modifying object that keeps on changing during the course of an iteration.

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

from, import

from and import are reserved keywords that are used to load any object into the program. This object can be a file, module, function, or else a variable.

When we don’t have to declare an object that is already declared but present in another file then we use from, import it to load it into the current program.

from file_1 import var

global

To change the scope of the local variable into a global we can define the variable as a global variable using the global keyword. Once it is defined as a global variable we can use it across other parts of the program.

a = 5
def func1():
    global a 
    a = 'hi'
func1()

def func2():
    print(a)   
func2()

# Output
hi

in

in is a keyword that belongs to membership operators. It helps us check the contents of an object and returns True if a value is present in the object or else returns False.

We can use in to check whether the given object present in the given collection. (It may be String, List, Set, Tuple OR Dict).

a = [1, 2]
b = 2
print(b in a)

True

is

is keyword to comparing the identity of the objects, and these objects are the variables that act as a reference to a memory object. If two identifiers point to the same memory object then they are equal in terms of reference and their reference id is the same.

a = "hi"
b = "hi"
print(a is b)

True

nonlocal

The keyword nonlocal is used to manipulate the variables from a nested function. When a variable is declared inside a function, the scope of the variable is bound within the function itself and its own nested functions if there is any.

def func():
    var = 5
    def func_nest():
        print(var)
    func_nest()
    print(var)
func()

# Output
4 
4

If we try to manipulate the var from func_nest() its value is bound within the nested function itself, so instead of declaring the variable we can make the variable nonlocal which makes var to be working in the function and its nested ones.

def func_outer():
    var = 5
    def func_nest():
        nonlocal var
        var = "hello"
        print("func_nest:-", var)
    func_nest()
    print("func_outer:-", var)
func_outer()

# Output
func_nest:- hello
func_outer:- hello

Thus making var to be available to functions inside the func_outer() and not available to functions outside the funct_outer() nonlocal provides flexibility to operate.

pass

pass is a statement that does nothing. It just informs the python interpreter that the pass statement is a line of code.

The main difference between a comment and a pass is that the interpreter completely ignores the commented line, whereas the pass is not ignored. This provides us to declare functions or loops or any conditions to be declared without writing any statements inside them.

In the below example of func() after indentation, the interpreter expects a line of code, but since the comment line is ignored by the interpreter, it is assumed there is no line of code after indent and throws an error.

def func():
    # comment
func()

Error:- expected an indent block

In the below code block, we have declared pass statement after every indentation such that these functions, for loop, if clause can be implemented in the future.

def func():
    pass
func()

for i in range(45):
    pass

if a > b:
    pass

return

The return statement is used at the last block of a function and makes the interpreter exit the function. If the return statement is not used then the function returns none automatically unless we are intent to print anything inside the function.

def func():
    a = 5
print(func())

# Output
None

The scenario could be different if we declare the return statement so that we can pass the manipulations performed by the function to the main program and use it in other parts of the program.

def func():
    a = 5
    return a
print(func())

# Output
5

yield

In python, the purpose yield is the same as the return statement. Both of them return something to the main block of the program which can be used for further operations.

a = 5
def func_1():
    return a
func_1()

def func_2():
    yield a
func_2

But the main difference is that yield returns a generator object that can be iterated. Also, yield is not an ending statement of the function, we can declare multiple yield statements.

The generated object needs to be converted into a list and iterated using for loop to print each item.

a = 5
def func():
    yield a+1
    yield a+2
    
obj = list(func())
for i in obj:
    print(i)

lambda

Lambda is used to create an anonymous function. Just like list comprehension lambda is an inline function, and its syntax is

lambda arguments : expression

Using the argument we pass the expression is evaluated and the result can be stored in a variable. We can pass multiple arguments separated by comma( , ).

a = lambda x, y : x / y
print(a(6, 2))

3

list keyword python

The list is an ordered and mutable sequence that can be used for storing, updating, deleting items. We can convert any data into a list by using the list() keyword.

Thus if an object is not able to be iterated but has some sequence of items then a list can be used to convert it into a list and access the items.

For example, when we use the map() method to get user input it returns a map object that is encoded. To access the items we can convert them into a list by using list() keyword.

a = map(int, input().split(" "))
print(a)

a = list(map(int, input().split(" ")))
print(a)

# user input
2 34 5

# Output
<map object at 0x000002215E8DF610>
[2, 34, 5]

all

all() is an in-built method in python that accepts an iterable sequence such as a list, dict, tuple, set, etc.,

  • all() returns True if all the items of the iterable are True
  • It also returns True is the iterable is empty
  • even if one item is False or 0 then it returns False
list_1 = []
list_2 = [5, True]
list_3 = [False, 7, "Python"]
dict = {5 : 6, True : 4}

all(list_1)    -> True
all(list_2)    -> True
all(list_3)    -> False
all(dict)      -> True

next

The next is a reserved word in python and returns the items of the iterable one by one, each time we declare next. It can be used when we don’t know the length of the iterable sequence.

The next() accepts the iterable sequence and a default value. This default value will be printed if the end of the sequence has reached.

next(iterable, default_value)

Each time we use the next keyword it prints the next value.

mylist = iter([2, 3, 5, "python"])

print(next(mylist))
print(next(mylist))

# Output
2
3

super

When a class is inherited some or all the behavior of the class will be inherited. Thus the inherited class is the subclass and the latter class is the parent class.

The super keyword is an OOPS concept that provides accessing the methods from the parent class into the child class.

super() keyword allows us to access the methods of the parent class and provides features such as Method Resolution Order( MRO ) used while multiple inheritances which is useful to get the information of how the methods are being called one after the other.

class Parent_class:
    def __init__(self):
        print("parent __init__")
    
class child_class(Parent_class):
    def __init__(self):
        super().__init__()
        print("child __init__")        

obj = child_class()

# Output
parent __init__
child __init__

id

id() is an in-built function in python that returns the identity of the object. This is a memory address value of the object. This id value can be the same if two objects have a non-overlapping lifetime.

a = 6
b = 6
print(id(a), id(b))

# Output
140727685875536  140727685875536

end

end is associated with python print statement and is used to end the print statement using the parameter specified. end keyword is present in python 3 and above.

By default, python ends the print statement with a new line, if end is defined it ends with the parameter that we pass into it.

print("hii", end = "@")
print("hello")

# Output
hii@hello

iter

iter is used to convert an iterable item into an iterator. It returns an iterable object that can be iterated one item at a time. Thus the iterable object can be passed into a for loop for printing the items.

For converting an object into iterable we can use the iter() keyword, which takes the object as a parameter. We can also print each item using the next keyword.

my_iter = iter([1, 2, 3, 4])
print(next(my_iter))
print(next(my_iter))

# Output
1
2

map

The map in python is used to convert all the items in an iterable object into the format without using the for loop which converts the items one by one through iteration.

map() takes a function that can be applied over an object and an iterable object that has the items to pass them to a function. Thus it processes all the items and transforms them using the function we specify.

It returns map objects as output in an encoded format and can be converted into other objects using the list() or set() methods.

# Converting list of strings into integer format
map_object = map(int, ["1", "2", "3", "4"])
print(map_object)
print(list(map_object))

# Output
<map object at 0x0000023BA379CDC0>
[1, 2, 3, 4]

FAQ’s in Python Keywords

What is the purpose of the def keyword in python?

def is a reserved keyword in python and is used for declaring a function. The function name with parenthesis and colon is followed by the def keyword. Whenever we use def it simply means we are declaring a function.

def func():
    statement 1
    statement 2
    - - - - -
    - - - - -

What is a keyword in python?

Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name, or any other identifier. To print the list of keywords in python we can use keyword.kwlist().

import keyword
print(keyword.kwlist)

What does python keyword from mean?

from is a reserved keyword that is used to load any object into the program. This object can be a file, module, function, or else a variable. This from keyword is associated with another keyword import for loading the files into our program.

from file_1 import var

What is a keyword argument in python?

Keyword arguments are values that are passed into a function and are identified by specific parameter names. These Keyword arguments are passed as key and value pairs usually separated by equality symbol or colon symbol.

When these keyword arguments are passed with a colon as a separator then it’s called a dictionary and is represented by a double asterisk ( ** ).

def func(**kwargs):
    for i in kwargs.items():
        print(i)
func(category = "python", difficulty = "medium")

# Output
('category', 'python')
('difficulty', 'medium')

keyword in python to see what version the program is running

In python, the sys module provides various functions and variables to get different information and perform manipulations on them.

import sys
print(sys.version)

3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:59:51) [MSC v.1928 64 bit (AMD64)]

What keyword is used to restart a script in python?

We need to pass sys.argv into os.execl() to restart the script in python.

import sys
import os

def restart_script():
    python = sys.executable
    os.execl(python, python, * sys.argv)

if __name__ == "__main__":
    action = input("Do you want to restart this program ? type yes or no - ")
    if action.lower().strip() in "y yes".split():
        restart_script()

In python, how to check if string is a reserved keyword

We can pass the string into keyword.iskeyword() method which returns True if the string is a keyword, else it returns False.

import keyword
print(keyword.iskeyword("def"))

# Output
True

What does the global keyword do in python?

To change the scope of the local variable into a global we can define the variable as a global variable using the global keyword.

a = 5
def func1():
    global a 
    a = 'hi'
    print(a)
func1()

# Output
hi

Which python keyword is used to define a loop?

There are two kinds of loops in Python and they are defined by their keywords, one is for loop and the other is while loop. We need to specify the indent at the end of the statement to enter into the loop.

for i in iterable:
    -----
    ----
while condition:
    ---
    ---

What keyword do we use to create a class, or a blueprint, for an object python?

For creating a class of an object we need to specify it using the class keyword. This class keyword is followed by the class name and indent.

class class_name:
     statement_1
     ----
     ----

Why is the “pass” keyword used for in python?

The pass is a statement that does nothing. It just informs the python interpreter that the pass statement is a line of code. This provides us to declare functions, classes or loops or any conditions to be declared without writing any statements inside them.

class class_name:
     pass

How to use a keyword to end a program in python?

To end a keyword we can use sys.exit() which can be imported from the python sys module. Wherever we use sys.exit it terminates the program at that point.

import sys
print("program started")
sys.exit()
print("last line")

# Output
program started

What is the use of the self keyword in python?

We can access the class variables using the instance of the class. To use these class variables inside any method in the class we can use the instance of the class such as self.class_var.

class ABC:
    class_var = 5
    def func(self):
        print(self.class_var)
ins = ABC()
ins.bart()

# Output
5

What is the python keyword for an approximation of a real number?

There are several keywords in python for approximating a number based on the requirement we can choose any of them. Such as round(), floor(), ceil(), etc.,

print(round(2.8))
3

print(floor(2.8))
2

print(ceil(2.2))
3

What is the difference between next and iter keyword in python?

In python, the next() keyword is used to print the elements of the sequence. Whereas the iter() is used to convert an object into an iterator. This iterable object can then be passed into next() to print the elements.

a = map(int, input().split(" "))
a = iter(a)
print(next(a))
print(next(a))
print(next(a))

# input
1 2 3

# Output
1
2
3

Which keyword ends a function in python?

return keyword is considered as a last statement of the function. Any commands written after the return are not considered in-function commands. Thus return ends the function in python.

def func_1():
     a = 5
     return a

Which keyword is used for creating a method inside a class in python?

Basically, every method is a function. Functions defined inside a class are known as methods, thus we can use the def keyword which is used for creating a function, to create a method in a class.

class ABC:
    def func_1():
        ---
        ---
    def func_2():
        ---
        ---

In python what does the private keyword do

In python, there is no keyword known as private. Instead, to make an identifier private we can declare its name by starting with a double underscore( __ ). These variables are not accessed from outside the class.

class ABC:
    __string1 = "hello world"        

Is print a keyword in python?

In python 3 and above print statement has been replaced with a print function. Thus print is not a keyword rather it’s a function.

What keyword negates a boolean value in python?

In python negating a value is just assigning an opposite value. For negating a boolean value we can use not keyword followed by a boolean value.

not True   -> False
not False  -> True

What are keyword args and var args in python

In python, we can pass a variable number of arguments using arguments and keyword arguments. arguments are represented using ( * ) and keyword arguments using ( ** ). The keyword argument can be referred to as dictionary key-value pairs.

a = [1, 2]
b =3
def func(*args, **kwargs):
    kwargs["version"] = "3.7"
    return a , kwargs

result = func(a, b, name = "python", version = "2.7")
print(result)

# Output
([1, 2], {'name': 'python', 'version': '3.7'})

What keyword in python makes a loop return to the beginning of the loop?

In python to return the control to the beginning of the loop, we can declare a continue() keyword, which stops further execution of that particular loop and brings control back to the start of the loop.

We can use a conditional statement such as if block to implement the continue keyword.

for i in range(5):
    if i == 3:
        continue
    print(i)

# Output
0
1
2
4

Which keyword is necessary in defining a generator function in python?

A generator is the same as a normal function. It is declared using the def keyword. But since the generator yields something we need to define a yield statement for making a normal function as a generator.

def func_1():
     a = 5
     yield a
     a += 2
     yield a

for i in func_1():
    print(i)

# Output
5
7

How do you use the join keyword in python?

join keywords is used to return a string and is also known as a string. It takes a sequence as a parameter and joins the items of the sequence based on the string object we pass into it.

seq = ["h", "e", "l", "l", "o"]
print("-".join(seq))

# Output
h-e-l-l-o

What does the keyword “try” in python do?

try keyword is used to handle the errors that might be caused due to logical or syntactical errors. It provides a block that can accept the line of code to be tested and returns errors if there are any.

If there is any error we can handle them using the except block.

try:
    result = 1/0
except ZeroDivisionError:
   print("division by zero not allowed")

# Output
division by zero not allowed

What is the significance of the keyword end in python?

keyword end is used for ending the print statement. By default print() will display the result and print a new line, in this case, we can declare the end keyword to join the print statement in the same line.

print("hello", end = " ")
print("world")

# Output
hello world

What does the static keyword do in python?

There is no static keyword in Python but the concept is implemented. In the Python OOPS concept, static variables are also known as class variables which are confined only to the class itself.

For defining a method as static we can declare @staticmethod which is an inbuilt decorator that tells that the method is confined to within the class itself.

What does with keyword do in python?

The with keyword manages the resources and exception handling. It is used to perform open/read/write etc., operations on files and also to handle an exception that occurs while handling any file.

Thus it also helps in program execution to continue without any errors.

In python, what is the none keyword

None is a constant that has no value and has its own NoneType data type. None has no value and is not a zero value or is not an empty string or a false value.

We can assign a none value to a variable or argument which can be further used.

empty_variable = None

In python when to use keyword arguments instead of positional?

In python, we pass keyword arguments when there is a requirement variable number of values to be passed to the function. These values are passed as key-value pairs, hence we can also perform dictionary operations for manipulation of values.

Note:- In function calling keyword arguments are passed only after any required positional arguments.

func(argument_1, argument_2, name = value1, contact = value2)

what is the await keyword in python

In python during asynchronous programming await keyword is used. No matter what the state of the program, when an await statement is declared the control waits till the completion of that particular line with the await keyword.

In the below code block the program waits for till the complete execution of the await expression and then executes the later commands.

import asyncio
await asyncio.sleep(1)

To display a value in the console, what python keyword do you use?

Python provides an in-built method known as print() to display values, strings, etc., We can also use sys.stdout to display the values provided by sys module in python

What does long keyword mean python?

long keyword in python converts any small data type into a long data type. long is the maximum available space for storing a value.

Usage of long is eliminated in python 3 and above instead we have only int and float.

Is break a keyword or an operator or what in python?

Basically, an operator is used to perform operations and will be associated with at least a single operand. Thus in python, the break is a keyword and is used to stop the iteration terminate the loop.

We can create a conditional statement associated with the break keyword to terminate the loop.

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

# Output
0  
1
2

What is the difference between token and keyword in python?

  • Python breaks each logical line into a sequence of elementary lexical components known as Tokens
  • Each token corresponds to sub-string of a logical line
  • These tokens are basically keywords, identifiers, delimeters, indents, literals, etc.,
  • Keywords are the reserved words in python and they have special purpose.
  • Each keywords has its own functionality and these cannot be used as identifiers or naming any value
  • Different types of keywords are def, class, list, for, if, else, etc.,

In python what is the difference between a identifier and a keyword?

  • Identifiers are basically the reference of an object, they are the name of the memory location. They are also used as variables.
  • Keyword is a reserved words and they have their own functionality and they cannot be used as for naming any value or object.

How does the or keyword work in python?

or keyword acts as a logical operator and returns a boolean value. It can be associated with a conditional statement to evaluate the result of the expressions. or returns False if both operands are False or else returns True every time

True or True     -> True
True or False    -> True
False or True    -> True
False or False   -> False

What happens if you overwrite a keyword in python?

No, we can’t overwrite keywords in Python. Keywords are reserved words and have their own functionality, so they cannot be altered.

Basically, the fundamental nature of keywords prohibits them to be changed to something or assigning new values. Thus we cannot overwrite keywords.

In multiprocessing python what is process keyword?

In multiprocessing, processes are defined by creating a Process object and then calling its start() method. The process follows the API of threading.Thread.

Depending on the platform we can start a process by using the following methods:-

  • fork
  • forkserver
  • spawn

What is character keyword in python?

Character keyword in python is represented using the chr() method and represents the string that is equal to the ASCII value we pass into the method. It does operation opposite to that performed by ord().

chr(56)  -> '8'
chr(25)  -> '\x19'
ord('r') -> 114

What is python array keyword?

The python array keyword is used to import an array module and create an array. Using this array we can create an array that has the same data type values and manipulate them.

import array as arr
a = arr.array("d", [1.2, 3.5, 6.4])

What is len keyword python?

len() keyword is an in-built method in python that is used to check the length of the sequence. It accepts the sequence as a parameter.

my_list = [1, 2, 3, 4]
len(my_list)

# Output
4

what is zip keyword in python?

zip keyword in python combines the values of the iterables based on their respective indexes. When we zip two lists elements of the same index are combined to form a tuple and are stored as a single element under another identifier.

When we zip two iterables of different lengths then the one with the least number of items defines the length of the resultant.

item_1 = (1, 2, 3, 4)
item_2 = ("hello", "python", "welcome", "to", "learn")
item_3 = zip(item_1, item_2)
print(item_3)
print(list(item_3))

# output
<zip object at 0x000002C8212BDD40>
[(1, 'hello'), (2, 'python'), (3, 'welcome'), (4, 'to')]

what is eval keyword python

eval() keyword is an in-built method that evaluates a string that we have passed as a parameter. It converts the string into an expression and returns the result of the expression as output.

The following steps are performed by eval:-

  • Parse expression
  • Compile to byte code
  • Evaluate it as python expression
  • Return the result of the evaluation
print(eval("5 * 5"))        -> 25
print(eval(" 2 * 'hii' "))  -> hiihii

What is the use dir keyword python?

dir() is an in-built method in python that accepts an object as a parameter and returns all the attributes that are associated with an object.

The object that we pass might be a list, string, or any random object, the dir returns all the methods, properties, and built-in properties.

# we are passing a list into dir method
my_list = [1, 2, 3]
print(dir(a))

# Output
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
 ---
 removed few line due to website length constraints
 ---
 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert',
 'pop', 'remove', 'reverse', 'sort']

In python, how to use the exception keyword?

The Python exception keyword is represented as except. It handles the errors raised by the try block. We can declare multiple except blocks to handle different kinds of errors.

Every try block is associated with an except block and vice versa.

Why event keyword in function python?

event keyword is used for communication between two threads, where one thread signals an event and the other thread wait for the signal.

This process is most useful in Thread Synchronization. So, one thread that is meant to produce the signal produces it, then the waiting thread gets activated.

What is the buffer keyword python?

For obvious reasons, the machine with 8GB RAM cannot open a file that takes 20GB of RAM. So we mention the buffer size while opening such files, so that machine exactly loads parts of file size equal to the buffer, one by one.

In the below code we are opening 2000000000 bytes( 2GB ) of file at once and processing it, once its done, the machine loads the next 2GB of file.

with open("file.csv", buffering = 2000000000) as file

What is keyword .abspath python?

The .abspath() is used to know the absolute version of the path. For example, we can know the exact folder location of a file and print it.

The absolute path belongs to the os module and takes the file name as a parameter.

import os
f = os.path.abspath("demo.py")

# Output
'C:\\Users\\OneDrive\\Desktop\\Data\\demo.py'

What is python compile keyword?

Python compile is used when we have python source code in a string format and would like to convert that into a code block. In such cases, we pass the string into the compile().

The parameters that we pass are the source which can be a string or anything that needs to be converted, file name, and mode (exec, eval, etc.,).

f = compile("[6] + [1, 2, 3, 4]", "[]", "exec")
exec(f)

# Output
[6, 1, 2, 3, 4]

What is the keyword for checking membership python?

In python, we have two keywords just for checking the membership, they are in and not in and they return boolean values based on the evaluation.

my_list = [1, 2, 3]
print(2 in my_list)

# Output
True

What is the python sys.argv keyword arguments

sys.argv() is an in-built method to print all the arguments that we pass into a program. It belongs to sys mobile and we can perform operations using the argument that we pass such as addition, subtraction, etc.,

While printing it returns the first argument as file name and then the arguments.

import sys
import sys
print(sys.argv)
if len(sys.argv)>1:
    add = sum(args for i in sys.argv if arg.isdigit())
    print(add)

# Input
python demo.py 1 3 5

# Output
9

what is the finally keyword in python?

In python finally block is declared after try and except blocks. It’s a code block that runs independently, which means the try and except blocks do not affect the execution of the finally block.

try :
    sum = 3 + "hello"
    print(sum)
except ArithmeticError():
    print("unsupported operand types")
finally:
    print("finally block ")

Is bytes a keyword in python

bytes() is an in-built method in python and has its own purpose of converting the object into byte format and storing them. The object returned by bytes can be modified.

bytes(4)   -> b'\x00\x00\x00\x00'

What is a sort keyword in python?

sort() is a built-in function in python that can be used to sort a list in both ascending and descending order.

list1 = [1, 5, 2, 4]

list1.sort()
print(list1) 

list1.sort(reverse = True)
print(list1)

# Output
[1, 2, 4, 5]
[5, 4, 2, 1]

What is python filter keyword?

filter() is an in-built function that returns the output by applying a sequence over a function. The first parameter it takes is the function and the second parameter is the sequence.

We can use lambda functions also while passing the function.

list1 = [1, 5, 2, 4, 3]
output = filter(lambda x : x%2 == 0, list1)
print(list(output))

# prints list of even numbers filtered from other
[2, 4]

What is the python sum keyword?

In python, the sum function is used to calculate the sum of all the items in an iterable. It takes iterable as the first parameter and the start value.

The start value is the value that gets added to the sum of the items in iterable. If the start value is not provided by default it is considered as zero.

list1 = [1, 5, 2, 4, 3]
output1 = sum(list1)
output2 = sum(list1, 25)
print(output1, output2)

# Output 
15, 40

What is the use of the python help keyword?

In python, help is an in-built method that is used to get information about a module or any object that we pass into it. We can pass the object or class or keyword or anything that has been already predefined.

It returns the complete documentation regarding the object that we pass.

help("def"), help("filter"), etc.,

Is type a keyword in python?

type() is an in-built method that has its own functionality and accepts an object or variable or anything and returns to which class the object belongs. Basically, it is used to know the data type of the value.

a = [1, 2]
type(a)

# Output
<class 'list'>