Python Interview Questions and Answers

1) What is Python? State some programming language features of Python.

Ans: Python is a modern powerful interpreted language with objects, modules, threads, exceptions, and automatic memory managements.

Python was introduced to the world in the year 1991 by Guido van Rossum

Salient features of Python are

-Simple & Easy: Python is simple language & easy to learn.

-Free/open source: it means everybody can use python without purchasing license.

-High level language: when coding in Python one need not worry about low-level details.

-Portable: Python codes are Machine & platform independent.

-Extensible: Python program supports usage of C/ C++ codes.

-Embeddable Language: Python code can be embedded within C/C++ codes &can be used a scripting language.

-Standard Library: Python standard library contains prewritten tools for programming.

-Build-in Data Structure: contains lots of data structure like lists, numbers & dictionaries.


2) What are the rules for local and global variables in Python?

Ans: If a variable is defined outside function then it is implicitly global. If variable is assigned new value inside the function means it is local. If we want to make it global we need to explicitly define it as global. Variable referenced inside the function are implicit global. Following code snippet will explain further the difference

#!/usr/bin/python

# Filename: variable_localglobal.py

def fun1(a):

print ‘a:’, a

a= 33;

print ‘local a: ‘, a

a = 100

fun1(a)

print ‘a outside fun1:’, a

def fun2():

global b

print ‘b: ‘, b

b = 33

print ‘global b:’, b

b =100

fun2()

print ‘b outside fun2’, b

Output:

$ python variable_localglobal.py

a: 100

local a: 33

a outside fun1: 100

b :100

global b: 33

b outside fun2: 33


3) How do we share global variables across modules in Python?

Ans: We can create a config file & store the entire global variable to be shared across modules or script in it. By simply importing config, the entire global variable defined it will be available for use in other modules.

For example: I want a, b & c to share between modules.

config.py :

a=0

b=0

c=0

module1.py:

import config

config.a = 1

config.b =2

config.c=3

print “ a, b & resp. are : “ , config.a, config.b, config.c

output of module1.py will be

1 2 3


4) How is memory managed in python?

Ans: Memory management in Python involves a private heap containing all Python objects and data structures. Interpreter takes care of Python heap and that the programmer has no access to it.

The allocation of heap space for Python objects is done by Python memory manager. The core API of Python provides some tools for the programmer to code reliable and more robust program.

Python also has a build-in garbage collector which recycles all the unused memory. When an object is no longer referenced by the program, the heap space it occupies can be freed. The garbage collector determines objects which are no longer referenced by the program frees the occupied memory and make it available to the heap space.

The gc module defines functions to enable /disable garbage collector:

gc.enable() -Enables automatic garbage collection.

gc.disable() – Disables automatic garbage collection.


5) Describe how to generate random numbers in Python.

Ans: The standard module random implements a random number generator.

There are also many other in this module, such as:

uniform(a, b) returns a floating point number in the range [a, b].

randint(a, b)returns a random integer number in the range [a, b].

random()returns a floating point number in the range [0, 1].

Following code snippet show usage of all the three functions of module random:

Note: output of this code will be different every time it is executed.

import random

i = random.randint(1,99)# i randomly initialized by integer between range 1 & 99

j= random.uniform(1,999)# j randomly initialized by float between range 1 & 999

k= random.random()# k randomly initialized by float between range 0 & 1

print(“i :” ,i)

print(“j :” ,j)

print(“k :” ,k)

Output :

(‘i :’, 64)

(‘j :’, 701.85008797642115)

(‘k :’, 0.18173593240301023)

Output:

(‘i :’, 83)

(‘j :’, 56.817584548210945)

(‘k :’, 0.9946957743038618)


6) Describe how exceptions are handled in python.

Ans: Errors detected during execution of program are called exceptions. Exceptions can be handled using the try..except statement. We basically put our usual statements within the try-block and put all our error handlers in the except-block.

try…except demo code:

>>> while True:

try:

x = int(raw_input(“Enter no. of your choice: “))

break

except ValueError:

print “Oops! Not a valid number. Attempt again”

Enter no. of your choice: 12ww

Oops! Not a valid number. Attempt again

Enter no. of your choice: hi there

Oops! Not a valid number. Attempt again

Enter no. of your choice: 22

>>>


7) When to use list vs. tuple vs. dictionary vs. set?

Ans: List is like array, it can be used to store homogeneous as well as heterogeneous data type (It can store same data type as well as different data type). List are faster compared to array. Individual element of List data can be accessed using indexing & can be manipulated.

List Code Snippet:

list = [“Sarah”,29,30000.00]

for i in range (3):

print list[i]

Output:

Sarah

29

30000.0

Tuples are similar to lists, but there data can be changed once created through the execution of program. Individual element of Tuples can be accessed using indexing.

Tuples Code Snippet: The Days

days = (“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”)

print days

(‘Sunday’, ‘Mondays’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)

Sets stores unordered values & have no index. And unlike Tuples and Lists, Sets can have no duplicate data, It is similar to Mathematical sets.

add() function can be used to add element to a set.

update() function can be used to add a group of elements to a set.

Copy() function can be used to create clone of set.

Set Code Snippet:

disneyLand = set ([‘Minnie Mouse’, ‘Donald Duck’, ‘Daisy Duck’, ‘Goofy’])

disneyLand.add(‘Pluto’)

print disneyLand

Output:

set([‘Goofy’, ‘Daisy Duck’, ‘Donald Duck’, ‘Minnie Mouse’, ’Pluto’])

Dictionary are similar to what their name is. In a dictionary, In python, the word is called a ‘key’, and the definition a ‘value’. Dictionaries consist of pairs of keys and their corresponding values.

Dictionary Code Snippet:

>>> dict = {‘India’: ‘Bharat’, ‘Angel’: ‘Mother Teresa’, ‘Cartoon’: ‘Mickey’}

>>>print dict[India]

Bharat

>>>print dict[Angel]

Mother Teresa


8) Explain the disadvantages of python.

Ans: Disadvantages of Python are:

Python isn’t the best for memory intensive tasks.

Python is interpreted language & is slow compared to C/C++ or java.

Python not a great choice for a high-graphic 3d game that takes up a lot of CPU.

Python is evolving continuously, with constant evolution there is little substantial documentation available for the language.

9) Is python compiled based or interpretive based language?

Ans: Python mostly used in scripting, is general purpose programming language which supports OOP Object oriented programming principles as supported by C++, Java, etc.

Python programs are written to files with extension .py . These python source code files are compiled to byte code (python specific representation and not binary code), platform independent form stored in .pyc files.

These byte code helps in startup speed optimization. These byte code are then subjected to Python Virtual Machine PVM where one by one instructions are read and executed. This is interpreter.


10) What built-in type does python provide?

Ans: Following are the most commonly used built-in types provided by Python:

Immutable built-in types of python

Numbers

Strings

Tuples

Mutable built-in types of python

List

Dictionaries

Sets


11) What is module in python?

Ans: Modules are way to structure python program. A module would have set of related functionalities. Each python program file (.py file) is a module, which imports other modules (object) to use names (attributes) they define

using object.attribute notation. All the top level names of a module are attributes, exported for use by the importer of this module.

Filename of a module turns out to be an object name where it is imported.

import re;  statement imports all the names defined in module re.

from statements can be used to import specific names from a module.

Both the above statements finds, compiles and loads (if not yet loaded) the module.

Python by default imports modules only once per file per process, when the very first import statement is encountered.

With from statement, names can be directly used. module name is not required.


12) What is package in python?

Ans: A folder of python programs (modules) is a package of modules. A package can have subfolders and modules.

A import statement can import packages and each import package introduces a namespace.

import folder1.subfolder2.module1

OR

from folder1.subfolder2.module1 import names

To import a package, __init__.py  file must be present in each of the folders, subfolders.


13) What is namespace in python?

Ans: Every name introduced in a python program has a place where it lives and can be looked for. This is its namespace. Consider it as a box where a variable name mapped to object is placed. Whenever the variable name is referenced, this box is looked out to get corresponding object.

For example, functions defined using def  have namespace of the module in which it is defined. And so 2 modules can define function with same name.

Modules and namespace go hand in hand. Each module introduces a namespace. Namespace helps in reusing name by avoiding name collision. Classes and functions are other namespace constructs.


14) What is scope in python?

Ans: Scope for names introduced in a python program is a region where it could be used, without any qualification. That is, scope is region where the unqalified reference to a name can be looked out in the namespace to find the object.

During execution, when a name is referred, python uses LEGB rule to find out the object. It starts looking out first into the local namespace. Then it searches name in enclosed namespace created by nested def and lambda. Then into global namespace which is the module in which it is defined and then finally into built-in namespace.

Example 1:

>>> def addxy(x,y):        # x, y are local. addxy is global

…     temp=x+y           # temp is local

…     print temp

…     return temp

>>> addxy(1,2)

3

3

Example 2:

>>> total = 0           # total is global

>>> def addxy(x,y):

…     global total

…     total = x+y

>>> x

100

>>> y

200

>>> addxy(x,y)

>>> total

300


15) What are the different ways of passing arguments to a function in python?

Ans: Different forms of calling function and passing arguments to functions in python:

Function definition Function Caller     Function call mapping to function definition

def func(x,y)        func(a,b)    Positional matching of argument

func(y=b, x=a)    Argument name matching

def func(x,y=10)   func(a)

func(a,b)    Default value for argument

def func(x,y, *tuple_arg)        func(a,b)

func(a,b,c) and many other arguments can be passed as positional arguments

Function with varying positional arguments stored in a tuple

Example:

def add(x,y, *tup):

temp = x+y

for elem in tup:

temp = temp + elem

return temp

print add(1,2) # prints 3

print add(1,2,3,4) # prints 10

def func(x,y, **dict_arg)        func(a,b)

func(a,b, c=10)

func(a,b, c=10, name=’abcd’ ) and many other arguments can be passed as keyword argument

Function with varying keyword arguments stored in dictionary.

Example:

def percentage(mks1, mks2, **dict):

total_mks = mks1 + mks2

return total_mks / float( dict[‘out_of’] )

print percentage(65, 50, out_of=150)


16) What is lambda in python?

Ans: lamda is a single expression anonymous function often used as inline function. It takes general form as:

lambda arg1 arg2 … : expression where args can be used

Example of lambda in python:

>>> triangle_perimeter = lambda a,b,c:a+b+c

>>> triangle_perimeter(2,2,2)

6


17)Difference between lamda and def :

Ans:

a. def can contain multiple expressions whereas lamda is a single expression function

b. def creates a function and assigns a name so as to call it later. lambda creates a function and returns the function itself

c. def can have return statement. lambda cannot have return statements

d. lambda can be used inside list, dictionary.


63) What is shallow copy and deep copy in python?

Ans: Object assignment does not copy object, it gets shared. All names point to same object.

For mutable object types, modifying object using one name, reflects changes when accessed with other name.

Example :

>>> l=[1,2,3]

>>> l2 = l

>>> l2.pop(0)

1

>>> l2

[2, 3]

>>> l

[2, 3]

A copy module overcomes above problem by providing copy() and deepcopy(). copy() creates a copy of an object, creating a separate entity.

Example of shallow copy copy():

>>> import copy

>>> copied_l = copy.copy(l)  # performs shallow copy

>>> copied_l.pop(0)

2

>>> copied_l

[3]

>>> l

[2, 3]

copy() does not perform recursive copy of object. It fails for compound object types.

Example program for shallow copy problems:

>>> l

[[1, 2, 3], [‘a’, ‘b’, ‘c’]]

>>> s_list=copy.copy(l)       # performs shallow copy

>>> s_list

[[1, 2, 3], [‘a’, ‘b’, ‘c’]]

>>> s_list[0].pop(0)

1

>>> s_list

[[2, 3], [‘a’, ‘b’, ‘c’]]

>>> l

[[2, 3], [‘a’, ‘b’, ‘c’]]          # problem of shallow copy on compund object types

To overcome this problem, copy module provides deepcopy(). deepcopy() creates and returns deep copy of compound object (object containing other objects)

Example for deep copy deepcopy():

>>> l

[[1, 2, 3], [‘a’, ‘b’, ‘c’]]

>>> deep_l = copy.deepcopy(l)

>>> deep_l

[[1, 2, 3], [‘a’, ‘b’, ‘c’]]

>>> deep_l[0].pop(0)

1

>>> deep_l

[[2, 3], [‘a’, ‘b’, ‘c’]]

>>> l

[[1, 2, 3], [‘a’, ‘b’, ‘c’]]


18)How exceptions are handle in python?

Ans: Exceptions are raised by Python when some error is detected at run time. Exceptions can be caught in the program using try and except statments. Once the exceptions is caught, it can be corrected in the program to avoid abnormal termination. Exceptions caught inside a function can be transferred to the caller to handle it. This is done by rethrowing exception using raise. Python also provide statements to be grouped inside finally which are executed irrespective of exception thrown from within try .

Example of handling exception and rethrowing exception:

def func2(a,b):

try:

temp = a/float(b)

except ZeroDivisionError:

print “Exception caught. Why is b = 0? Rethrowing. Please handle”

raise ZeroDivisionError

finally:

print “Always executed”

def func1():

a=1

b=1

print “Attempt 1: a=”+str(a)+”, b=”+str(b)

func2(a,b)

b=a-b

print “Attempt 2: a=”+str(a)+”, b=”+str(b)

try:

func2(a,b)

except ZeroDivisionError:

print “Caller handling exception”

func1()

Output:

Attempt 1: a=1, b=1

Always executed

Attempt 2: a=1, b=0

Exception caught. Why is b = 0? Rethrowing. Please handle

Always executed

Caller handling exception


19) Give a regular expression that validates email id using python regular expression module re

Ans: Python provides a regular expression module re

Here is the re that validates a email id of .com and .co.in subdomain:

re.search(r”[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$”,”[email protected]”)


20) Explain file opertaions in python

Ans: Python provides open()  to open a file and open() returns a built-in type file object. The default mode is read.

fread = open(“1.txt”) is equivalent to fread = open(“1.txt”, “r”), where fread is where the file object returned by open() is stored.

Python provides read(), readline() and readlines() functions to read a file. read() reads entire file at once. readline() reads next line from the open file. readlines() returns a list where each element is a line of a file.

The file can also be open in write mode. Python provides write() to write a string in a file, writelines() to write a sequence of lines at once.

The built-in type file object has close() to which is called for all open files.


21) What standard do you follow for Python coding guidlines?

Ans: PEP 8 provides coding conventions for the Python code. It describes rules to adhere while coding in Python. This helps in better readability of code and thereby better understanding and easy maintainability. It covers from

code indentation, amount of space to use for indentation, spaces v/s tabs for indentation, commenting, blank lines, maximum line length, way of importing files, etc.


22) What is pass in Python?

Ans: Pass is no-operation Python statement. It indicates nothing is to be done. It is just a place holder used in compund statements as they cannot be left blank.

Example of using pass statement in Python:

>>> if x==0:

…     pass

… else:

…     print “x!=0”


23) What are iterators in Python?

Ans: Iterators in Python are used to iterate over a group of elements, containers, like list. For a container to support iterator, it must provide __iter__().

container.__iter__() :

This returns an iterator object.

Iterator protocol:

The iterator object is required to support the iterator protocol. Iterator protocol is implemented by an iterator object by providing definition of the following 2 functions:

1. iterator.__iter__() :

It returns the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.

2. iterator.__next__() :

It returns the next item from the container. If there are no further items, raise the StopIteration exception.

Example of iterator on list:

>>> a=[1,2,3]

>>> i1= a.__iter__()   # creating an iterator using __iter__() on container

>>> i1

>>> i2= iter(a)        # creating another iterator using iter() which calls __iter__() on container

>>> i2

>>> i1.next()

1

>>> next(i1)           # calls i1.next()

2

>>> next(i2)

1

Iterators are required to implement __iter__ which returns the iterator (self) . Hence it can be used with for in

>>> for x in i1:

…   print x

3


24) What are generators in Python?

Ans: Generators are way of implementing iterators. Generator function is a normal function except that it contains yield expression in the function definition making it a generator function. This function returns a generator

Iterator known as generator. To get the next value from a generator, we use the same built-in function as for iterators: next() . next() takes care of calling the generator’s __next__() method.

When a generator function calls yield, the “state” of the generator function is frozen; the values of all variables are saved and the next line of code to be executed is recorded until next() is called again. Once it is, the

Generator function simply resumes where it left off. If next() is never called again, the state recorded during the yield call is (eventually) discarded.

Example of generators:

def gen_func_odd_nums():

odd_num = 1

while True:

yield odd_num         # saves context and return from function

odd_num = odd_num + 2

generator_obj = gen_func_odd_nums();

print “First 10 odd numbers:”

for i in range(10):

print next(generator_obj) # calls generator_obj.__next__()

Output:

First 10 odd numbers:

1

3

5

7

9

11

13

15

17

19


25) How do you perform unit testing in Python?

Ans: Python provides a unit tesing framework called unittest . unittest module supports automation testing, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.


26) What is slicing in Python?

Ans: Slicing in Python is a mechanism to select a range of items from Sequence types like strings, list, tuple, etc.

Example of slicing:

>>> l=[1,2,3,4,5]

>>> l[1:3][2, 3]

>>> l[1:-2][2, 3]

>>> l[-3:-1]      # negative indexes in slicing

[3, 4]

>>> s=”Hello World”

>>> s[1:3]

‘el’

>>> s[:-5]

‘Hello ‘

>>> s[-5:]

‘World’


27) Explain OOP principle inheritance in Python

Ans: Classes can derive attributes from other classes via inheritance. The syntax goes:

class DeriveClass( BaseClass):

If the base class is present in other module, the syntax for derivation changes to:

class DeriveClass( module.BaseClass):

Python supports overriding of base class functions by derive class. This helps in adding more functionality to be added in overriden function in derived class if required.

Python supports limited form of multiple inheritance as:

class DeriveClass( BaseClass1, BaseClass2, …):

Where an attribute if not found in DeriveClass are then searched in BaseClass1 and their parent then BaseClass2 and their parents and so on. With new style, Python avoids diamond problem of reaching common base class from

Multiple paths by lineraly searching base classes in left to right order.


28) What is docstring in Python?

Ans: Docstring or Python documentation string is a way of documenting Python modules, functions, classes. PEP 257 standardize the high-level structure of docstrings. __doc__ attribute can be used to print the docstring.

Example of defining docstring:

>>> def test_doc_string():

…    “”” this is a docstring for function test_doc_string “””

>>> test_doc_string.__doc__

‘this is a docstring for function test_doc_string ‘


29) Define python?

Ans: Python is simple and easy to learn language compared to other programming languages. Python was introduced to the world in the year 1991 by Guido van Rossum. It is a dynamic object oriented language used for developing

software. It supports various programming languages and have a massive library support for many other languages. It is a modern powerful interpreted language with objects, modules, threads, exceptions, and automatic memory managements.

Salient features of Python are:

-Simple & Easy: Python is simple language & easy to learn.

-Free/open source: it means everybody can use python without purchasing license.

-High level language: when coding in Python one need not worry about low-level details.

-Portable: Python codes are Machine & platform independent.

-Extensible: Python program supports usage of C/ C++ codes.

-Embeddable Language: Python code can be embedded within C/C++ codes & can be used a scripting language.

-Standard Library: Python standard library contains prewritten tools for programming.

-Build-in Data Structure: contains lots of data structure like lists, numbers & dictionaries.


30) Define a method in Python?

Ans: A function on object x is a method which is called as x.name(arguments…). Inside the definition of class, methods are defined as functions:

class C:

def meth(self, atg):

return arg*2+self.attribute


31) Define self?

Ans: ‘self’ is a conventional name of method’s first argument. A method which is defined as meth(self, x ,y ,z) is called as a.meth(x, y, z) for an instance of a class in which definition occurs and  is called as meth(a, x ,y, z).


32) Describe python usage in web programming?

Ans: Python is used perfectly for web programming and have many special features to make it easy to use. Web frame works, content management systems, WebServers, CGI scripts, Webclient programming, Webservices, etc are the

features supported by python. Python language is used to create various high end applications because of its flexibility.


33) Is there any tool used to find bugs or carrying out static analysis?

Ans: Yes. PyChecker is the static analysis tool used in python to find bugs in source code, warns about code style and complexity etc. Pylint is a tool that verifies whether a module satisfies standards of coding and makes it

possible to add custom feature and write plug-ins.


34) Rules for local and global variables in python?

Ans: In python, the variables referenced inside a function are global. When a variable is assigned new value anywhere in the body of a function then it is assumed as local. In a function, if a variable ever assigned new value then

the variable is implicitly local and explicitly it should be declared as global. If all global references require global then you will be using global at anytime. You’d declare as global each reference to built-in function or to component of module which is imported. The usefulness of global declaration in identifying side-effects is defeated by this clutter.


35) How to find methods or attributes of an object?

Ans: Built-in dir() function of Python ,on an instance shows the instance variables as well as the methods and class attributes defined by the instance’s class and all its base classes alphabetically. So by any object as argument

to dir() we can find all the methods & attributes of the object’s class.

Following code snippet shows dir() at work :

class Employee:

def __init__(self,name,empCode,pay):

self.name=name

self.empCode=empCode

self.pay=pay

print(“dir() listing all the Methods & attributes of class Employee”)

print dir(e)

Output:

dir() listing all the Methods & attributes of class Employee

[ ‘__init__’, ’empCode’, ‘name’, ‘pay’]


35) Is there any equivalent to scanf() or sscanf()?

Ans: No.  Usually, the easy way to divide line into whitespace-delimited words for simple input parsing use split() method of string objects. Then, decimal strings are converted to numeric values using float() or int(). An

optional “sep” parameter is supported by split() which is useful if something is used in the place of whitespace as separator. For complex input parsing, regular expressions are powerful then sscanf() of C and perfectly suits

for the task.


36) Define class?

Ans: Class is a specific object type created when class statement is executed. To create instances objects, class objects can be used as templates which represent both code and data specific to datatype. In general, a class is

based on one or many classes known as base classes. It inherits methods and attributes of base classes. An object model is now permitted to redefine successively using inheritance. Basic accessor methods are provided by

generic Mailbox for subclasses and mailbox like MaildirMailbox, MboxMailbox, OutlookMailbox which handle many specific formats of mailbox.


37) How to prevent blocking in content() method of socket?

Ans: Commonly, select module is used to help asynchronous I/O.


38) In python, are there any databases to DB packages?

Ans: Yes. Bsddb package is present in Python 2.3 which offers an interface to BerkeleyDatabase library. It Interface to hashes based on disk such as GDBM and DBM are included in standard python.


39)How do we share global variables across modules in Python?

Ans: We can create a config file & store the entire global variable to be shared across modules or script in it. By simply importing config, the entire global variable defined it will be available for use in other modules.

For example I want a, b & c to share between modules.

config.py :

a=0

b=0

c=0

module1.py:

import config

config.a = 1

config.b =2

config.c=3

print “ a, b & resp. are : “ , config.a, config.b, config.c

Output:

module1.py will be

1 2 3


40)  How can we pass optional or keyword parameters from one function to another in Python?

Ans: Gather the arguments using the * and ** specifiers in the function’s parameter list. This gives us positional arguments as a tuple and the keyword arguments as a dictionary. Then we can pass these arguments while calling

another function by using * and **:

def fun1(a, *tup, **keywordArg):

keywordArg[‘width’]=’23.3c’

Fun2(a, *tup, **keywordArg)


41)  Explain pickling and unpickling.

Ans: Pickle is a standard module which serializes & de-serializes a python object structure. Pickle module accepts any python object converts it into a string representation & dumps it into a file(by using dump() function) which

can be used later, process is called pickling. Whereas unpickling is process of retrieving original python object from the stored string representation for use.


42) Explain how python is interpreted.

Ans: Python program runs directly from the source code. Each type Python programs are executed code is required. Python converts source code written by the programmer into intermediate language which is again translated it into the native language / machine language that is executed. So Python is an Interpreted language.


43) How is memory managed in python?

Ans: Memory management in Python involves a private heap containing all Python objects and data structures. Interpreter takes care of Python heap and that the programmer has no access to it. The allocation of heap space for Python objects is done by Python memory manager. The core API of Python provides some tools for the programmer to code reliable and more robust program. Python also has a build-in garbage collector which recycles all the unused memory. When an object is no longer referenced by the program, the heap space it occupies can be freed. The garbage collector determines objects which are no longer referenced by the sprogram frees the occupied memory and make it available to the heap space. The gc module defines functions to enable /disable                         garbage collector:

gc.enable() -Enables automatic garbage collection.

gc.disable() – Disables automatic garbage collection.


44) Explain indexing and slicing operation in sequences

Ans: Different types of sequences in python are strings, Unicode strings, lists, tuples, buffers, and xrange objects. Slicing & indexing operations are salient features of sequence. indexing operation allows to access a particular

item in the sequence directly ( similar to the array/list indexing) and the slicing operation allows to retrieve a part of the sequence. The slicing operation is used by specifying the name of the sequence followed by an

optional pair of numbers separated by a colon within square brackets say S[startno.:stopno]. The startno in the slicing operation indicates the position from where the slice starts and the stopno indicates where the slice

will stop at. If the startno is ommited, Python will start at the beginning of the sequence. If the stopno is ommited, Python will stop at the end of the sequence..

Following code will further explain indexing & slicing operation:

>>> cosmeticList =[‘lipsstick’,’facepowder’,eyeliner’,’blusher’,kajal’]

>>> print “Slicing operation :”,cosmeticList[2:]

Slicing operation :[‘eyeliner’,’blusher’,kajal’]

>>>print “Indexing operation :”,cosmeticList[0]

“Indexing operation :lipsstick


45) Explain how to make Forms in python.

Ans: As python is scripting language forms processing is done by Python. We need to import cgi module to access form fields using FieldStorage class.

Every instance of class FieldStorage (for ‘form’) has the following attributes:

form.name: The name of the field, if specified.

form.filename: If an FTP transaction, the client-side filename.

form.value: The value of the field as a string.

form.file: file object from which data can be read.

form.type: The content type, if applicable.

form.type_options: The options of the ‘content-type’ line of the HTTP request, returned as a dictionary.

form.disposition: The field ‘content-disposition’; None if unspecified.

form.disposition_options: The options for ‘content-disposition’.

form.headers: All of the HTTP headers returned as a dictionary.

A code snippet of form handling in python:

import cgi

form = cgi.FieldStorage()

if not (form.has_key(“name”) and form.has_key(“age”)):

print “

Name & Age not Entered

print “Fill the Name & Age accurately.”

return

print “

name:”, form[“name”].value

print “

Age:”, form[“age”].value


46) Describe how to implement Cookies for Web python.

Ans: A cookie is an arbitrary string of characters that uniquely identify a session. Each cookie is specific to one Web site and one user.

The Cookie module defines classes for abstracting the concept of cookies. It contains following method to creates cookie

Cookie.SimpleCookie([input])

Cookie.SerialCookie([input]

Cookie.SmartCookie([input])

for instance following code creates a new cookie ck-

import Cookie

ck= Cookie.SimpleCookie ( x )


47) What are uses of lambda?

Ans: It used to create small anonymous functions at run time. Like e.g.

def fun1(x):

return x**2

print fun1(2)

it gives you answer 4

the same thing can be done using

sq=lambda x: x**2

print sq(2)

it gives the answer 4


48) When do you use list vs. tuple vs. dictionary vs. set?

Ans: List and Tuple are both ordered containers. If you want an ordered container of constant elements use tuple as tuples are immutable objects.


49) When you need ordered container of things, which will be manipulated, use lists.

Ans: Dictionary is key, value pair container and hence is not ordered. Use it when you need fast access to elements, not in ordered fashion. Lists are indexed and index of the list cannot be “string” e.g. list [‘myelement’] is not a valid statement in python.


50) Do they know a tuple/list/dict when they see it?

Ans: Dictionaries are consisting of pair of keys and values.like {’key’:’value’}.

book={’cprog’:’1024′,’c++’:’4512′}

Keys are unique but values can be same. The main difference between list and tuple is you can change the list but you cannot change the tuple. Tuple can be used as keys in mapping where list is not.


51) Why was the language called as Python?

Ans: At the same time he began implementing Python, Guido van Rossum was also reading the published scripts from “Monty Python’s Flying Circus” (a BBC comedy series from the seventies, in the unlikely case you didn’t know). It

occurred to him that he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.


52) What is used to represent Strings in Python? Is double quotes used for String representation or single quotes used for String representation in Python?

Ans: Using Single Quotes (‘)

You can specify strings using single quotes such as ‘Quote me on this’ . All white space i.e. spaces and tabs are preserved as-is.

Using Double Quotes (“)

Strings in double quotes work exactly the same way as strings in single quotes. An example is “What’s your name?”

Using Triple Quotes (”’ or “””)

You can specify multi-line strings using triple quotes. You can use single quotes and double quotes freely within the triple quotes. An example is

”’This is a multi-line string. This is the first line.

This is the second line.

“What’s your name?,” I asked.

He said “Bond, James Bond.”


53) Why cannot lambda forms in Python contain statements?

Ans: A lambda statement is used to create new function objects and then return them at runtime that is why lambda forms in Python did not contain statement.


54) Which of the languages does Python resemble in its class syntax?

Ans: C++ is the appropriate language that Python resemble in its class syntax.


55) Does Python support strongly for regular expressions? What are the other languages that support strongly for regular expressions?

Ans: Yes, python strongly support regular expression. Other languages supporting regular expressions are: Delphi, Java, Java script, .NET, Perl, Php, Posix, python, Ruby, Tcl, Visual Basic, XML schema, VB script, Visual Basic 6.


56) Why is not all memory freed when Python exits?

Ans: Objects referenced from the global namespaces of Python modules are not always de-allocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the

C library that are impossible to free (e.g. a tool like the one Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.

If you want to force Python to delete certain things on de-allocation, you can use the at exit module to register one or more exit functions to handle those deletions.


57) What is a Lambda form? Explain about assert statement?

Ans: The lambda form:

Using lambda keyword tiny anonymous functions can be created. It is a very powerful feature of Python which declares a one-line unknown small function on the fly. The lambda is used to create new function objects and then

return them at run-time. The general format for lambda form is:

lambda parameter(s): expression using the parameter(s)

For instance k is lambda function-

>>> k= lambda y: y + y

>>> k(30)

60

>>> k(40)

80

The assert statement:

The build-in assert statement of python introduced in version 1.5 is used to assert that something is true. Programmers often place assertions at the beginning of a function to check for valid input, and after function call

to check for valid output. Assert statement can be removed after testing of program is over. If assert evaluates to be false, an AssertionError exception is raised. AssertionError exceptions can be handled with the try-except

statement.

The general syntax for assert statement is:

assert Expression[, Arguments]


58)  Explain the role of repr function.

Ans: Python can convert any value to a string by making use of two functions repr() or str(). The str() function returns representations of values which are human-readable, while repr() generates representations which can be read

by the interpreter. repr() returns a machine-readable representation of values, suitable for an exec command. Following code sniipets shows working of repr() & str() :

def fun():

y=2333.3

x=str(y)

z=repr(y)

print ” y :”,y

print “str(y) :”,x

print “repr(y):”,z

fun()

output

y : 2333.3

str(y) : 2333.3

repr(y) : 2333.3000000000002


59)  What is LIST comprehensions features of Python used for?

Ans: LIST comprehensions features were introduced in Python version 2.0, it creates a new list based on existing list. It maps a list into another list by applying a function to each of the elements of the existing list. List

comprehensions creates lists without using map() , filter() or lambda form.


60) How do you make a higher order function in Python?

Ans: A higher-order function accepts one or more functions as input and returns a new function. Sometimes it is required to use function as data. To make high order function , we need to import functools module The

functools.partial() function is used often for high order function.


61) Explain how to copy an object in Python.

Ans: There are two ways in which objects can be copied in python. Shallow copy & Deep copy. Shallow copies duplicate as minute as possible whereas Deep copies duplicate everything. If a is object to be copied then

-copy.copy(a) returns a shallow copy of a.

-copy.deepcopy(a) returns a deep copy of a.


62) How do I convert a string to a number?

Ans: Python contains several built-in functions to convert values from one data type to another data type.

The int function takes string and coverts it to an integer.

s = “1234” # s is string

i = int(s) # string converted to int

print i+2

1236

The float function converts strings into float number.

s = “1234.22” # s is string

i = float(s) # string converted to float

print i

1234.22


63) What is a negative index in python?

Ans: Python arrays & list items can be accessed with positive or negative numbers (also known as index). For instance our array/list is of size n, then for positive index 0 is the first index, 1 second, last index will be n-1. For

negative index, -n is the first index, -(n-1) second, last negative index will be – 1. A negative index accesses elements from the end of the list counting backwards.

An example to show negative index in python.

>>> import array

>>> a= [1, 2, 3]

>>> print a[-3]

1

>>> print a[-2]

2

>>> print a[-1]

3


64) How do you make an array in Python?

Ans: The array module contains methods for creating arrays of fixed types with homogeneous data types. Arrays are slower then list. Array of characters, integers, floating point numbers can be created using array module. array

(typecode[, intializer]) Returns a new array whose items are constrained by typecode, and initialized from the optional initialized value. Where the typecode can be for instance ‘c’ for character value, ‘d’ for double, ‘f’ for float.


65) Explain how to create a multidimensional list.

Ans: There are two ways in which Multidimensional list can be created:

By direct initializing the list as shown below to create multidimlist below

>>>multidimlist = [ [227, 122, 223],[222, 321, 192],[21, 122, 444]]

>>>print multidimlist[0]

>>>print multidimlist[1][2]

Output:

[227, 122, 223]

192

The second approach is to create a list of the desired length first and then fill in each element with a newly created lists demonstrated below :

>>>list=[0]*3

>>>for i in range(3):

>>> list[i]=[0]*2

>>>for i in range (3):

>>> for j in range(2):

>>> list[i][j] = i+j

>>>print list

Output:

[[0, 1], [1, 2], [2, 3]]


66) Explain how to overload constructors (or methods) in Python.

Ans: _init__ () is a first method defined in a class. when an instance of a class is created, python calls __init__() to initialize the attribute of the object.

Following example demonstrate further:

class Employee:

def __init__(self, name, empCode,pay):

self.name=name

self.empCode=empCode

self.pay=pay

e1 = Employee(“Sarah”,99,30000.00)

e2 = Employee(“Asrar”,100,60000.00)

print(“Employee Details:”)

print(” Name:”,e1.name,”Code:”, e1.empCode,”Pay:”, e1.pay)

print(” Name:”,e2.name,”Code:”, e2.empCode,”Pay:”, e2.pay)

Output:

Employee Details:

(‘ Name:’, ‘Sarah’, ‘Code:’, 99, ‘Pay:’, 30000.0)

(‘ Name:’, ‘Asrar’, ‘Code:’, 100, ‘Pay:’, 60000.0)


67) Describe how to send mail from a Python script.

Ans: The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine.

A sample email is demonstrated below.

import smtplib

SERVER = smtplib.SMTP(‘smtp.server.domain’)

FROM = [email protected]

TO = [“[email protected]”] # must be a list

SUBJECT = “Hello!”

TEXT = “This message was sent with Python’s smtplib.”

# Main message

message = “””

From: Sarah Naaz < [email protected] >

To: CarreerRide [email protected]

Subject: SMTP email msg

This is a test email. Acknowledge the email by responding.

“”” % (FROM, “, “.join(TO), SUBJECT, TEXT)

server = smtplib.SMTP(SERVER)

server.sendmail(FROM, TO, message)

server.quit()


68)  Describe how to generate random numbers in Python.

Ans: Thee standard module random implements a random number generator.\

There are also many other in this module, such as:

uniform(a, b) returns a floating point number in the range [a, b].

randint(a, b)returns a random integer number in the range [a, b].

random()returns a floating point number in the range [0, 1].

Following code snippet show usage of all the three functions of module random:

Note: output of this code will be different evertime it is executed.

import random

i = random.randint(1,99)# i randomly initialized by integer between range 1 & 99

j= random.uniform(1,999)# j randomly initialized by float between range 1 & 999

k= random.random()# k randomly initialized by float between range 0 & 1

print(“i :” ,i)

print(“j :” ,j)

print(“k :” ,k)

Output

(‘i :’, 64)

(‘j :’, 701.85008797642115)

(‘k :’, 0.18173593240301023)

Output

(‘i :’, 83)

(‘j :’, 56.817584548210945)

(‘k :’, 0.9946957743038618)


69) What is the optional statement used in a try except statement in Python?

Ans: There are two optional clauses used in try except statements:

1. Else clause: It is useful for code that must be executed when the try block does not create any exception

2. Finally clause: It is useful for code that must be executed irrespective of whether an exception is generated or not.


70) What is used to create Unicode string in Python?

Ans: Add u before the string

>>> u ‘test’


71) What are the uses of List Comprehensions feature of Python?

Ans: List comprehensions help to create and manage lists in a simpler and clearer way than using map(), filter() and lambda. Each list comprehension consists of an expression followed by a clause, then zero or more for or if

clauses.


72) Which all are the operating system that Python can run on?

Ans: Python can run of every operating system like UNIX/LINUX, Mac, Windows, and others.


73) What is the statement that can be used in Python if a statement is required syntactically but the program requires no action?

Ans: Pass is a no-operation/action statement in python

If we want to load a module and if it does not exist, let us not bother, let us try to do other task. The following example demonstrates that.

Try:

Import module1

Except:

Pass


74) What is the Java implementation of Python popularly known as?

Ans: Jython


75) What is the method does join() in python belong?

Ans: String method


76)Does python support switch or case statement in Python? If not what is the reason for the same?

Ans: No. You can use multiple if-else, as there is no need for this.


77) How is the Implementation of Pythons dictionaries done?

Ans: Using curly brackets -> {}

E.g.: {‘a’:’123′, ‘b’:’456′}


78) What is the language from which Python has got its features or derived its features?

Ans: Most of the object oriented programming languages to name a few are C++, CLISP and Java is the language from which Python has got its features or derived its features.


79) What are the disadvantages of the Python programming language?

Ans: One of the disadvantages of the Python programming language is it is not suited for fast and memory intensive tasks

Naveen E

Naveen E

Author

Hola peeps! Meet an adventure maniac, seeking life in every moment, interacting and writing at Asha24.