PYTHON Programming Question & Answer
PYTHON Programming Question & Answer
Q-1: What is Python, what are the benefits of using it, and what do you
understand of PEP 8?
Python is one of the most successful interpreted languages. When you write a
Python script, it doesn’t need to get compiled before execution. Few other interpreted
languages are PHP and Javascript.
PEP 8.
Q-2: What is the output of the following Python code fragment? Justify your
answer.
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
PYTHON Interview Questions Answers
You may erroneously expect list1 to be equal to [10] and list3 to match with [‘a’],
thinking that the list argument will initialize to its default value of [] every time there
is a call to the extendList.
However, the flow is like that a new list gets created once after the function is
defined. And the same gets used whenever someone calls the extendList method
without a list argument. It works like this because the calculation of expressions (in
default arguments) occurs at the time of function definition, not during its invocation.
List1 and list3 are hence operating on the same default list, whereas list2 is running
on a separate object that it has created on its own (by passing an empty list as the
value of the list parameter).
The definition of the extendList function can be changed in the following manner.
return list
list1 = [10]
list2 = [123]
list3 = ['a']
Q-3: What is the statement that can be used in Python if the program requires
no action but requires it syntactically?
PYTHON Interview Questions Answers
The pass statement is a null operation. Nothing happens when it executes. You
should use the “pass” keyword in lowercase. If you write “Pass,” you’ll face an error
like “NameError: name Pass is not defined.” Python statements are case sensitive.
Q-4: What’s the process to get the home directory using ‘~’ in Python?
You need to import the os module, and then just a single line would do the rest.
import os
print (os.path.expanduser('~'))
Output:
/home/runner
Here is the list of most commonly used built-in types that Python supports:
● You can use PyChecker, which is a static analyzer. It identifies the bugs in
PYTHON Interview Questions Answers
Python projects and also reveals the style and complexity related bugs.
● Another tool is Pylint, which checks whether the Python module satisfies the
coding standard.
Python decorator is a relative change that you do in Python syntax to adjust the
functions quickly.
Q-8: What is the principal difference between a list and the tuple?
The principal difference between a list and the tuple is that the former is mutable
while the tuple is not.
● Python uses private heaps to maintain its memory. So the heap holds all the
Python objects and the data structures. This area is only accessible to the
Python interpreter; programmers can’t use it.
● And it’s the Python memory manager that handles the Private heap. It does
the required allocation of the memory for Python objects.
● Python employs a built-in garbage collector, which salvages all the unused
memory and offloads it to the heap space.
Q-10: What are the principal differences between the lambda and def?
Q-11: Write a reg expression that confirms an email id using the python reg
expression module “re”?
Check out the “re” expression that can check the email id for .com and .co.in
subdomain.
import re
print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
Q-12: What do you think is the output of the following code fragment? Is there
any error in the code?
print (list[10:])
The result of the above lines of code is []. There won’t be any error like an IndexError.
You should know that trying to fetch a member from the list using an index that
exceeds the member count (for example, attempting to access list[10] as given in the
question) would yield an IndexError. By the way, retrieving only a slice at the starting
index that surpasses the no. of items in the list won’t result in an IndexError. It will
just return an empty list.
Q-13: Is there a switch or case statement in Python? If not then what is the
reason for the same?
No, Python does not have a Switch statement, but you can write a Switch function
and then use it.
Q-14: What is a built-in function that Python uses to iterate over a number
sequence?
Range() generates a list of numbers, which is used to iterate over for loops.
for i in range(5):
print(i)
PYTHON Interview Questions Answers
● range(stop)
■ stop: It is the no. of integers to generate and starts from zero. eg.
range(3) == [0, 1, 2].
● range([start], stop[, step])
■ Start: It is the starting no. of the sequence.
■ Stop: It specifies the upper limit of the sequence.
■ Step: It is the incrementing factor for generating the sequence.
● Points to note:
■ Only integer arguments are allowed.
■ Parameters can be positive or negative.
■ The range() function in Python starts from the zeroth index.
Q-15: What are the optional statements possible inside a try-except block in
Python?
There are two optional clauses you can use in the try-except block.
Slicing is a string operation for extracting a part of the string, or some part of a list.
In Python, a string (say text) begins at index 0, and the nth character stores at
position text[n-1]. Python can also perform reverse indexing, i.e., in the backward
direction, with the help of negative numbers. In Python, the slice() is also a
constructor function which generates a slice object. The result is a set of indices
PYTHON Interview Questions Answers
mentioned by range(start, stop, step). The slice() method allows three parameters. 1.
start – starting number for the slicing to begin. 2. stop – the number which indicates
the end of slicing. 3. step – the value to increment after each index (default = 1).
Python has support for formatting any value into a string. It may contain quite
complex expressions.
One of the common usages is to push values into a string with the %s format
specifier. The formatting operation in Python has the comparable syntax as the C
function printf() has.
Let’s take an example. We have an “str” variable holding a string value. We can’t
mutate the container, i.e., the string, but can modify what it contains that means the
value of the variable.
An index is an integer data type which denotes a position within an ordered list or a
string.
In Python, strings are also lists of characters. We can access them using the index
which begins from zero and goes to the length minus one.
For example, in the string “Program,” the indexing happens like this:
Program 0 1 2 3 4 5
A docstring is a unique text that happens to be the first statement in the following
Python constructs:
Python has given us many built-in functions such as print() and provides the ability
to create user-defined functions.
1. Built-in, and
2. User-defined.
The built-in functions happen to be part of the Python language. Some of these are
print(), dir(), len(), and abs() etc.
Step-1: to begin the function, start writing with the keyword def and then mention the
function name.
Step-2: We can now pass the arguments and enclose them using the parentheses. A
colon, in the end, marks the end of the function header.
Step-3: After pressing an enter, we can add the desired Python statements for
execution.
A function in Python gets treated as a callable object. It can allow some arguments
and also return a value or multiple values in the form of a tuple. Apart from the
function, Python has other constructs, such as classes or the class instances which
fits in the same category.
The purpose of a function is to receive the inputs and return some output.
The return is a Python statement which we can use in a function for sending a value
back to its caller.
Python will treat that variable as local in the function-level scope. Any changes made
to that variable will remain local and will not reflect outside the function.
This scheme also has the advantage of bringing more time and space efficiency
because it leaves the need for creating local copies.
On the contrary, the disadvantage could be that a variable can get changed
accidentally during a function call. Hence, the programmers need to handle the code
to avoid such uncertainty.
It is not at all necessary for a function to return any value. However, if needed, we
can use None as a return value.
The continue is a jump statement in Python which moves the control to execute the
next iteration in a loop leaving all the remaining instructions in the block unexecuted.
PYTHON Interview Questions Answers
The continue statement is applicable for both the “while” and “for” loops.
Signature: id(object)
It accepts one parameter and returns a unique identifier associated with the input
object.
We use *args as a parameter in the function header. It gives us the ability to pass N
(variable) number of arguments.
Please note that this type of argument syntax doesn’t allow passing a named
argument to the function.
The output:
I
am
Learning
Python
We can also use the **kwargs syntax in a Python function declaration. It lets us pass
N (variable) number of arguments which can be named or keyworded.
PYTHON Interview Questions Answers
The output:
The main() is the entry point function which happens to be called first in most
programming languages.
Since Python is interpreter-based, it sequentially executes the lines of the code one-
by-one.
Python also does have a Main() method. But it gets executed whenever we run our
Python script either by directly clicking it or starts it from the command line.
We can also override the Python default main() function using the Python if
statement. Please see the below code.
print("Welcome")
print("__name__ contains: ", __name__)
def main():
print("Testing the main function")
if __name__ == '__main__':
main()
The output:
Welcome
__name__ contains: __main__
PYTHON Interview Questions Answers
The __name__ is a unique variable. Since Python doesn’t expose the main() function,
so when its interpreter gets to run the script, it first executes the code which is at level
0 indentation.
To see whether the main() gets called, we can use the __name__ variable in an if
clause compares with the value “__main__.”
Python’s print() function always prints a newline in the end. The print() function
accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can
change the end character in a print statement with the value of our choice using this
parameter.
Python provides a break statement to exit from a loop. Whenever the break hits in the
code, the control of the program immediately exits from the body of the loop.
The break statement in a nested loop causes the control to exit from the inner
iterative block.
PYTHON Interview Questions Answers
The continue statement makes the loop resume from the next iteration.
On the contrary, the pass statement instructs to do nothing, and the remainder of the
code executes as usual.
In Python, the len() is a primary string function. It determines the length of an input
string.
11
The chr() function got re-added in Python 3.2. In version 3.0, it got removed.
It returns the string denoting a character whose Unicode code point is an integer.
For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the
string ‘Ҽ’.
The ord(char) in Python takes a string of size one and returns an integer denoting the
Unicode code format of the character in case of a Unicode type object, or the value
of the byte if the argument is of 8-bit string type.
>>> ord("z")
122
Python provides the rstrip() method which duplicates the string but leaves out the
whitespace characters from the end.
The rstrip() escapes the characters from the right end based on the argument value,
PYTHON Interview Questions Answers
str.rstrip([char sequence/pre>
#Example
test_str = 'Programming '
# The trailing whitespaces are excluded
print(test_str.rstrip())
Whitespace represents the characters that we use for spacing and separation.
Python provides this built-in isalpha() function for the string handling purpose.
It returns True if all characters in the string are of alphabet type, else it returns False.
Python’s split() function works on strings to cut a large piece into smaller chunks, or
sub-strings. We can specify a separator to start splitting, or it uses the space as one
by default.
#Example
str = 'pdf csv json'
print(str.split(" "))
print(str.split())
The output:
Python provides the join() method which works on strings, lists, and tuples. It
combines them and returns a united value.
Python provides the title() method to convert the first letter in each word to capital
format while the rest turns to Lowercase.
#Example
str = 'lEaRn pYtHoN'
print(str.title())
The output:
Learn Python
CPython has its core developed in C. The prefix ‘C’ represents this fact. It runs an
interpreter loop used for translating the Python-ish code to C language.
The tests confirmed that PyPy is nearly five times faster than the CPython. It
currently supports Python 2.7.
Python supports GIL (the global interpreter lock) which is a mutex used to secure
access to Python objects, synchronizing multiple threads from running the Python
bytecodes at the same time.
Python ensures safe access to threads. It uses the GIL mutex to set synchronization.
If a thread loses the GIL lock at any time, then you have to make the code thread-safe.
For example, many of the Python operations are atomic such as calling the sort()
method on a list.
Python implements a heap manager internally which holds all of its objects and
data structures.
This heap manager does the allocation/deallocation of heap space for objects.
They are similar to sequences, just like the lists. However, There are some differences
between a tuple and list; the former doesn’t allow modifications whereas the list does.
Also, the tuples use parentheses for enclosing, but the lists have square brackets in
their syntax.
The collection is a set of keys having a single associated value. We can call it a
hash, a map, or a hashmap as it gets called in other programming languages.
Sets are unordered collection objects in Python. They store unique and immutable
objects. Python has its implementation derived from mathematics.
A dictionary has a group of objects (the keys) map to another group of objects (the
values). A Python dictionary represents a mapping of unique Keys to Values.
They are mutable and hence will not change. The values associated with the keys
PYTHON Interview Questions Answers
A Python list is a variable-length array which is different from C-style linked lists.
Internally, it has a contiguous array for referencing to other objects and stores a
pointer to the array variable and its length in the list head structure.
Python supports object-oriented programming and provides almost all OOP features
to use in programs.
A Python class is a blueprint for creating the objects. It defines member variables
and gets their behavior associated with them.
We can make it by using the keyword “class.” An object gets created from the
constructor. This object represents the instance of the class.
programmer
After we added the attributes, we can go on to define the functions. Generally, we call
them methods. In the method signature, we always have to provide the first
argument with a self-keyword.
Manager
We can specify the values for the attributes at runtime. We need to add an init
method and pass input to the object constructor. See the following example
demonstrating this.
Manager
Inheritance is an OOP mechanism which allows an object to access its parent class
features. It carries forward the base class functionality to the child.
PYTHON Interview Questions Answers
The common code rests with the base class, and the child class objects can access
it via inheritance. Check out the below example.
desk = Desktop()
print(desk.processor, desk.os, desk.ram)
lap = Laptop()
The output:
The composition is also a type of inheritance in Python. It intends to inherit from the
PYTHON Interview Questions Answers
base class but a little differently, i.e., by using an instance variable of the base class
acting as a member of the derived class.
def get_PC(self):
return "%s cpu & %s ram" % (self.processor, self.ram)
class Tablet():
make = "Intel"
def __init__(self, processor, ram, make):
self.PC = PC(processor, ram) # Composition
self.make = make
def get_Tablet(self):
return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram,
self.make)
if __name__ == "__main__":
tab = Tablet("i7", "16 GB", "Intel")
print(tab.get_Tablet())
PYTHON Interview Questions Answers
Errors are coding issues in a program which may cause it to exit abnormally.
On the contrary, exceptions happen due to the occurrence of an external event which
interrupts the normal flow of the program.
Python lays down Try, Except, Finally constructs to handle errors as well as
Exceptions. We enclose the unsafe code indented under the try block. And we can
keep our fall-back code inside the except block. Any instructions intended for
execution last should come under the finally block.
try:
print("Executing code in the try block")
print(exception)
except:
print("Entering in the except block")
finally:
For example, if we want the user to enter only odd numbers, else will raise an
exception.
try:
value = int(input("Enter an odd number- "))
if value%2 == 0:
raise ValueError("Exited due to invalid input!!!")
else:
print("Value entered is : %s" % value)
except ValueError as ex:
print(ex)
break
Iterators in Python are array-like objects which allow moving on the next element. We
use them in traversing a loop, for example, in a “for” loop.
Python library has a no. of iterators. For example, a list is also an iterator and we can
start a for loop over it.
The collection type like a list, tuple, dictionary, and set are all iterable objects whereas
they are also iterable containers which return an iterator while traversing.
A Generator is a kind of function which lets us specify a function that acts like an
iterator and hence can get used in a “for” loop.
PYTHON Interview Questions Answers
print(next(generate()))
Python closures are function objects returned by another function. We use them to
eliminate code redundancy.
In the example below, we’ve written a simple closure for multiplying numbers.
def multiply_number(num):
def product(number):
'product() here is a closure'
return num * number
return product
num_2 = multiply_number(2)
print(num_2(11))
print(num_2(24))
num_6 = multiply_number(6)
print(num_6(1))
22
48
PYTHON Interview Questions Answers
Python decorator gives us the ability to add new behavior to the given objects
dynamically. In the example below, we’ve written a simple example to display a
message pre and post the execution of a function.
def decorator_sample(func):
def decorator_hook(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return decorator_hook
@decorator_sample
def product(x, y):
"Function to multiply two numbers."
return x * y
print(product(3, 3))
Let’s take the example of building site statistics. For this, we first need to break up
the key-value pairs using a colon(“:”). The keys should be of an immutable type, i.e.,
so we’ll use the data-types which don’t allow changes at runtime. We’ll choose from
an int, string, or tuple.
However, we can take values of any kind. For distinguishing the data pairs, we can
use a comma(“,”) and keep the whole stuff inside curly braces({…}).
<class 'dict'>
>>> print(site_stats)
To fetch data from a dictionary, we can directly access it using the keys. We can
enclose a “key” using brackets […] after mentioning the variable name corresponding
to the dictionary.
>>> print(site_stats["traffic"])
We can even call the get method to fetch the values from a dict. It also let us set a
default value. If the key is missing, then the KeyError would occur.
tecbeamers.com
We can use the “for” and “in” loop for traversing the dictionary object.
print("++++++++++++++++++++++++")
++++++++++++++++++++++++
We can add elements by modifying the dictionary with a fresh key and then set the
value to it.
We can even join two dictionaries to get a bigger dictionary with the help of the
update() method.
Another method we can use is the pop() function. It accepts the key as the
parameter. Also, a second parameter, we can pass a default value if the key doesn’t
exist.
We can use the Python “in” operator to test the presence of a key inside a dict object.
True
Earlier, Python also provided the has_key() method which got deprecated.
For example, the below code will return all the numbers from 10 to 20 and store them
in a list.
>>> print(alist)
A dictionary has the same syntax as was for the list comprehension but the
difference is that it uses curly braces:
For example, the below code will return all the numbers 10 to 20 as the keys and will
PYTHON Interview Questions Answers
>>> print(adict)
The syntax for generator expression matches with the list comprehension, but the
difference is that it uses parenthesis:
For example, the below code will create a generator object that generates the values
from 10 to 20 upon using it.
Yes
While using the iterators, sometimes we might have a use case to store the count of
iterations. Python gets this task quite easy for us by giving a built-in method known
as the enumerate().
We can use this object directly in the “for” loops or transform it into a list of tuples by
calling the list() method. It has the following signature:
enumerate(iterable, to_begin=0)
Arguments:
iterable: array type object which enables iteration
to_begin: the base index for the counter is to get started, its default value is 0
print(list(enumerate(alist)) )
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))
[(2, 'b'), (3, 'a'), (4, 'n'), (5, 'a'), (6, 'n'), (7, 'a')]
The globals() function in Python returns the current global symbol table as a
dictionary object.
Python maintains a symbol table to keep all necessary information about a program.
This info includes the names of variables, methods, and classes used by the
program.
PYTHON Interview Questions Answers
All the information in this table remains in the global scope of the program and
Python allows us to retrieve it using the globals() method.
Signature: globals()
Arguments: None
# Test Code
ret = fn()
print(ret)
12
The zip method lets us map the corresponding index of multiple containers so that
we can use them as a single unit.
Signature:
zip(*iterators)
Arguments:
Python iterables or collections (e.g., list, string, etc.)
Returns:
print (out)
The output of zip() is : {('jerry', 33, 'R&D'), ('jake', 44, 'IT'), ('john', 28, 'Accounts'), ('tom',
32, 'HR')}
But the instance or non-static variables are altogether different for different objects.
The programming languages like C++ and Java need to use the static keyword to
make a variable as the class variable. However, Python has a unique way to declare
a static variable.
All names initialized with a value in the class declaration become the class variables.
And those which get assigned values in the class methods become the instance
variables.
# Example
class Test:
aclass = 'programming' # A class variable
def __init__(self, ainst):
self.ainst = ainst # An instance variable
print(test1.aclass)
print(test2.aclass)
print(test1.ainst)
PYTHON Interview Questions Answers
print(test2.ainst)
print(Test.aclass)
programming
programming
1
2
programming
The ternary operator is an alternative for the conditional statements. It combines true
or false values with a statement that you need to test.
x, y = 35, 75
smaller = x if x < y else y
print(smaller)
The self is a Python keyword which represents a variable that holds the instance of
an object.
● copy.copy() function
■ It makes a copy of the file from source to destination.
■ It’ll return a shallow copy of the parameter.
● copy.deepcopy() function
■ It also produces the copy of an object from the source to
destination.
■ It’ll return a deep copy of the parameter that you can pass to the
function.
In Python, the docstring is what we call the docstrings. It sets a process of recording
Python functions, modules, and classes.
Q-90: Which Python function will you use to convert a number to a string?
For converting a number into a string, you can use the built-in function str(). If you
want an octal or hexadecimal representation, use the inbuilt function oct() or hex().
Yes, we can use the Python debugger (pdb) to debug any Python program. And if we
start a program using pdb, then it lets us even step through the code.
Q-92: List down some of the PDB commands for debugging Python programs?
In Python, we can use the sys module’s settrace() method to set up trace hooks and
monitor the functions inside a program.
You need to define a trace callback method and pass it to the settrace() function.
The callback should specify three arguments as shown below.
import sys
def demo2():
print 'in demo2()'
def demo1():
print 'in demo1()'
demo2()
sys.settrace(trace_calls)
demo1()
Generators give us the ability to hold the execution of a function or a step as long as
we want to keep it. However, here are a few examples where it is beneficial to use
generators.
PYTHON Interview Questions Answers
The yield keyword can turn any function into a generator. It works like a standard
return keyword. But it’ll always return a generator object. Also, a method can have
multiple calls to the yield keyword.
def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.
We can use the ”.join() method which combines all elements into one and returns as
a string.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)
PYTHON Interview Questions Answers
But remember, we can’t change the list after turning it into a tuple because it
becomes immutable.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)
● Set doesn’t allow duplicate entries so that the conversion will remove any
such item.
● A set is an ordered collection, so the order of list items would also change.
However, we can use the set() function to convert a list into a Set.
weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)
However, we can achieve the conversion by breaking the list into a set of pairs and
PYTHON Interview Questions Answers
Passing the tuples into the dict() function would finally turn them into a dictionary.
weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
Q-98: How do you count the occurrences of each item present in the list
without explicitly mentioning them?
Unlike sets, lists can have items with the same values.
In Python, the list has a count() function which returns the occurrences of a
particular item.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))
#output: 3
We’ll use the list comprehension along with the count() method. It’ll print the
frequency of each of the items.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print([[x,weekdays.count(x)] for x in set(weekdays)])
#output: [['wed', 1], ['sun', 2], ['thu', 1], ['tue', 1], ['mon', 3], ['fri', 1]]
NumPy is a Python package for scientific computing which can deal with large data
sizes. It includes a powerful N-dimensional array object and a set of advanced
PYTHON Interview Questions Answers
functions.
Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for
this.
Q-100: What are different ways to create an empty NumPy array in Python?
There are two methods which we can apply to create empty NumPy arrays.
import numpy
numpy.array([])
numpy.empty(shape=(0,0))