Interview Question Python
Interview Question Python
Interview Question Python
com/python-interview-questions/
This page will guide you on how to crack any python programming interview,
including:
A local scope refers to the local objects available in the current function.
A global scope refers to the objects available throught the code execution since
their inception.
A module-level scope refers to the global objects of the current module accessible
in the program.
An outermost scope refers to all the built-in names callable in the program. The
objects in this scope are searched last to find the name referenced.
Note: Local scope objects can be synced with global scope objects using keywords
such as global.
9. What is Scope Resolution in Python?
Sometimes objects within the same scope have the same name but function
differently. In such cases, scope resolution comes into play in Python
automatically. A few examples of such behaviour are:
Python modules namely 'math' and 'cmath' have a lot of functions that are common to
both of them - log10(), acos(), exp() etc. To resolve this amiguity, it is
necessary to prefix them with their respective module, like math.exp() and
cmath.exp().
Consider the code below, an object temp has been initialized to 10 globally and
then to 20 on function call. However, the function call didn't change the value of
the temp globally. Here, we can observe that Python draws a clear line between
global and local variables treating both their namespaces as separate identities.
temp = 10 # global-scope variable
def func():
temp = 20 # local-scope variable
print(temp)
def func():
global temp
temp = 20 # local-scope variable
print(temp)
@names_decorator
def say_hello(name1, name2):
return 'Hello ' + name1 + '! Hello ' + name2 + '!'
None Type
None keyword represents the null values in Python. Boolean equality operation can
be performed using these NoneType objects.
Class Name Description
NoneType Represents the NULL values in Python
Numeric Types
There are three distint numeric types - integers, floating-point numbers, and
complex numbers. Additionally, booleans are a sub-type of integers.
Class Name Description
int Stores integer literals including hex, octal and binary numbers as integers
float Stores literals containing decimal values and/or exponent sign as floating-
point numbers
complex Stores complex number in the form (A + Bj) and has attributes: real and
imag
bool Stores boolean value (True or False)
Note: The standard library also includes fractions to store rational numbers and
decimal to store floating-point numbers with user-defined precision.
Sequence Types
According to Python Docs, there are three basic Sequence Types - lists, tuples, and
range objects. Sequence types have the in and not in operators defined for their
traversing their elements. These operators share the same priority as the
comparison operations.
Class Name Description
list Mutable sequence used to store collection of items.
tuple Immutable sequence used to store collection of items.
range Represents an immutable sequence of numbers generated during execution.
str Immutable sequence of Unicode code points to store textual data.
Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str .
Mapping Types
A mapping object can map hashable values to random objects in Python. Mappings
objects are mutable and there is currently only one standard mapping type, the
dictionary.
Class Name Description
dict Stores comma-separated list of key: value pairs
Set Types
Currently, Python has two built-in set types - set and frozenset. set type is
mutable and supports methods like add() and remove(). frozenset type is immutable
and can't be modified after creation.
Class Name Description
set Mutable unordered collection of distinct hashable objects
frozenset Immutable collection of distinct hashable objects
Note: set is mutable and thus cannot be used as key for a dictionary. On the other
hand, frozenset is immutable and thus, hashable, and can be used as a dictionary
key or as an element of another set.
Modules
Module is an additional built-in type supported by the Python Interpreter. It
supports one special operation, i.e., attribute access: mymod.myobj, where mymod is
a module and myobj references a name defined in m's symbol table. The module's
symbol table resides in a very special attribute of the module __dict__, but direct
assignment to this module is neither possible nor recommended.
Callable Types
Callable types are the types to which function call can be applied. They can be
user-defined functions, instance methods, generator functions, and some other
built-in functions, methods and classes.
Refer the documentation at docs.python.org for a detailed view into the callable
types.
mulFive = myWrapper(5)
print(mulFive(2)) # output => 10
15. What is pass in Python?
The pass keyword represents a null operation in Python. It is generally used for
the purpose of filling up empty blocks of code which may execute during runtime but
has yet to be written. Without the pass statement in the following code, we may run
into some errors during code execution.
def myEmptyFunc():
# do nothing
pass
Shallow Copy is a bit-wise copy of an object. The copied object created has an
exact copy of the values in the original object. If either of the values are
references to other objects, just the reference addresses for the same are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even
duplicates the objects referenced by the source object.
from copy import copy, deepcopy
## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
So how does that make a difference? It sure does, because unlike range(), xrange()
doesn't generate a static list, it creates the value on the go. This technique is
commonly used with an object type generators and has been termed as "yielding".
Packages allow for hierarchial structuring of the module namespace using dot
notation. As, modules help avoid clashes between global variable names, in a
similary manner, packages help avoid clashes between module names.
Creating a package is easy since it makes use of the system's inherent file
structure. So just stuff the modules into a folder and there you have it, the
folder name as the package name. Importing a module or its contents from this
package requires the package name as prefix to the module name joined by a dot.
Note: You can technically import the package as well, but alas, it doesn't import
the modules within the package to the local namespace, thus, it is practically
useless.
19. What are global, protected and private attributes in Python?
Global variables are public variables that are defined in the global scope. To use
the variable in the global scope inside a function, we use the global keyword.
Protected attributes are attributes defined with a underscore prefixed to their
identifier eg. _sara. They can still be accessed and modified from outside the
class they are defined in but a responsible developer should refrain from doing so.
Private attributes are attributes with double underscore prefixed to their
identifier eg. __ansh. They cannot be accessed or modified from the outside
directly and will result in an AttributeError if such an attempt is made.
20. What is self in Python?
Self is a keyword in Python used to define an instance or an object of a class. In
Python, it is explicity used as the first paramter, unlike in Java where it is
optional. It helps in disinguishing between the methods and attributes of a class
from its local variables.
# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")
22. What is break, continue and pass in Python?
Break The break statement terminates the loop immediately
and the control flows to the statement after the body of the loop.
Continue The continue statement terminates the current iteration of the
statement,
skips the rest of the code in the current iteration and the control flows to the
next iteration of the loop.
Pass As explained above, pass keyword in Python is generally used to fill-up empty
blocks
and is similar to an empty statement represented by a semi-colon in languages such
as Java, C++, Javascript etc.
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
pass
if (p == 0):
current = p
break
elif (p % 2 == 0):
continue
print(p) # output => 1 3 1 3 1
Pickling
Pickling is the name of the serialization process in Python. Any object in Python
can be serialized into a byte stream and dumped as a file in the memory. The
process of pickling is compact but pickle objects can be compressed further.
Moreover, pickle keeps track of the objects it has serialized and the serialization
is portable across versions.
The function used for the above process is pickle.dump().
Unpickling
Unpickling is the complete inverse of pickling. It deserializes the byte stream to
recreate the objects stored in the file, and loads the object to memory.
The function used for the above process is pickle.load().
Note: Python has another, more primitive, serialization module called marshall,
which exists primarily to support .pyc files in Python and differs significantly
from pickle.
def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
def __iter__(self):
self.pos = 0
return self
def __next__(self):
if(self.pos < len(self.numbers)):
self.pos += 1
return self.numbers[self.pos - 1]
else:
raise StopIteration
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration
33. What is slicing in Python?
As the name suggests, ‘slicing’ is taking parts of.
Syntax for slicing is [start : stop : step]
start is the starting index from where to slice a list or tuple
stop is the ending index or where to sop.
step is the number of steps to jump.
Default value for start is 0, stop is number of items, step is 1.
Slicing can be done on strings, arrays, lists, and tuples.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]
34. Explain how can you make a Python Script executable on Unix?
Script file must begin with #!/usr/bin/env python
35. Explain how to delete a file in Python?
Use command os.remove(file_name)
import os
os.remove("ChangedFile.csv")
print("File Removed!")
36. Explain split() and join() functions in Python?
You can use split() function to split a string based on a delimiter to a list of
strings.
You can use join() function to join a list of strings based on a delimiter to give
a single string.
string = "This is a string."
string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
print(string_list) #output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list)) #output: This is a string.
37. What is the difference between Python Arrays and lists?
Arrays in python can only contain elements of same data types i.e., data type of
array should be homogeneous. It is a thin wrapper around C language arrays and
consumes far less memory than lists.
Lists in python can contain elements of different data types i.e., data type of
lists can be heterogeneous. It has the disadvantage of consuming large memory.
import array
for i in a:
print(i, end=' ') #OUTPUT: 1 2 3
a = [1, 2, 'string']
for i in a:
print(i, end=' ') #OUTPUT: 1 2 string
38. What does *args and **kwargs mean?
*args
return mul
Q - Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'], what is the
output of ["".join([i, j]) for i, j in zip(list1, list2)]?
['s', 'a', 'r', 'a', 'a', 'n', 's', 'h']
['s', 'r', 'a', 's', 'a', 'a', 'n', 'h']
['sa', 'ra', 'an', 'sh']
['sa', 'sa', 'sn', 'sh', 'ra', 'ra', 'rn', 'rh', 'aa', 'aa', 'an', 'ah', 'sa',
'sa', 'sn', 'sh']