Python Interview Questions
Python Interview Questions
Note: These instructions should be used with the HadoopExam Apache OOzie: Professional Trainings.
Where it is executed and you can do hands on with trainer.
Cloudera CCA175 (Hadoop and Spark Developer Hands-on Certification available with total 90 solved
problem scenarios. Click for More Detail)
Cloudera CCPDE575 (Hadoop BigData Data Engineer Professional Hands-on Certification available
with total 79 solved problem scenarios. Click for More Detail)
Cloudera CCA159 Data Analyst Certification Practice Questions (Total 73 HandsOn Practice Questions)
1
Who all are the user of the Python Programming?
Ans: Python programming is not only for the IT developers, it is mainly used by professionals who are
working in Finance domain, Analytics, Data Scientists, Researchers and IT Developers etc.
Ans: Python is a high level language as other programming language C, C++, Java, Scala etc.
Ans: Low level language which can be understood by underline machine, you can say machine language
or assembly language are low level language. And computers can run the program which is written in
low language only.
Ans: High level language are first needs to be converted to low level language e.g. Java Virtual Machine
does of java language. This is an extra step which makes executing code slower compare to low level
language.
Ans : Writing program using high level language can have following advantages.
- Easier to program
- They are portable, e.g. write program on Windows OS that can be executed on IOS without any
or very less change. In case of low level language, you have to write program again for different
OS.
Q5. How high level language are converted to low level language?
Ans: There are two way by which high level languages are converted into low level language.
- Interpreter
- Compiler
Ans: It does not do lot of conversion, it reads the program and directly execute on the computer. Hence,
this is relatively faster than compiler.
Ans: Compiler reads your program written in high level language e.g. Java Code and it is known as source
file and once source file is compiled it will be converted into object code(also executable). This
executable need not be converted in any other form. Now you will have run time environment where
you can run this executable on any operating system.
2
Ans: Python is an interpreter language. Hence, it is not required to be compiled and then executer (as in
case of Java you have to do this).
Ans : Python source file has .py extension like test.py , is a python file.
- Syntax Error: It is any syntactical error in the program. E.g. (8.value, is not correct)
- Runtime Error
- Semantic Error
Ans: These errors only appears when you run the program. This is also known as exceptions.
Ans: Catching such errors are not easy. Until and unless you test the output. It means your program will
run without any issue. It will successfully complete. But when you see the result than only you can say
that there is an issue e.g. You want to add two numbers 2 and 3 and expected answer is 5, but program
generate 6 (because instead of + sign, * has been used.).
Ans: Interpreter convert high level language line by line but for compiler entire program will be
translated in low level language.
Ans: This is a category of the data e.g. 23 is an int , 23.7 id a float and Amit is a string type.
Ans: Its name to a value. You can refer a particular value using variable name like Amit it is a value but
will be referred using a variable called name
Ans: Function is a collection of statements, which is defined once and then call it later to do some
executions. Below is the function definition example
def total_course_durations(c1,c2):
training=curse_duration()
training.hours=c1.hours+c2.hours
training.minutes=c1.minutes+c2.minutes
training.seconds=c1.seconds+c2.seconds
3
return training
total_duration=total_course_durations(hadoop_training,spark_training)
return: It is a return statements. Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
Q17. How do you convert data from one data type to another data types?
Ans: There are various functions available, which can help you convert data from one data types to
another data type. See the example below
Ans: Python module is any python file with .py extension, which contains functions and variables are
known as Python Module. To use module in our current program we have to import it first. There are in-
built modules which are provided by Python itself e.g. import math (Here, math is a Python module)
Ans: Function, which return a value is known as fruitful function. E.g math.sqrt(4), it will return 2
Ans: Function which does not return a value is known as void function.
Q21. What are the all ways, by which you can import a module in Python?
Ans: Python provides two ways by which you can import the Python module.
- Using import statement e.g. import math, it will give you an object of math module.
- Another way, import only, which you want from module e.g. from math import pi now you can
use pi directly without dot notation.
Q22. How can I import the all the functions and variable from a module?
Ans: You can import everything from your module using * operator as below.
4
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
However, this is a bad practice. It will overwrite all the variables and functions which you have defined in
your program. So it is suggested, to avoid this.
Ans : Function definition, is the way by which you define a function as below.
def total_course_durations(c1,c2):
training=curse_duration()
training.hours=c1.hours+c2.hours
training.minutes=c1.minutes+c2.minutes
training.seconds=c1.seconds+c2.seconds
return training
Function Object: This is created by a function definition. Name of the function total_course_durations
is a variable, which points to function object.
Ans: Parameters are defined by the names that appear in a function definition, whereas arguments are
the values actually passed to a function when calling it. Parameters define what types of arguments a
function can accept. For example, given the function definition:
Value1, value2 and kwargs are parameters of func1. However, when calling func1, for example:
Ans: A variable which you define inside the function is known as local variable, you can not use local
variable outside the function. Below two variables course1 and course2 are local and cannot be
accessed outside the function.
def total_course_durations(c1,c2):
course1=c1
course2=c2
Ans: A value created by an import statement that provides access to the values defined in a module.
e.g import math , here math is a module object and using dot notation you can access the variables
defined in this module for instance math.pi
5
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
An object's docstring is defined by including a string constant as the first statement in the object's
definition.
def my_function():
"""Do nothing, but document it.
No, really, it doesn't do anything.
"""
You can print this doc string using: print my_function.__doc__
Q29. Which operator will help you get the remainder and quotient value in Python?
Ans: There are two mathematical operator to help you get quotient and remainder.
Getting remainder using % modulus operator and / to get the quotient value for example
quotient = 10 / 3 # will result 3
remainder = 10 % 3 #will result 1
- a>0 or a<10 # this condition will return true, if either a is greater than 0 or less than 10 e.g.
a=100 than also it will return true.
- not (10 >100) # It will return true. Because first 10 >100, it means it is false but we are
negating this condition. Hence, it will become true.
6
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
Ans: A part of the code, which is never executed is known as dead code. This is generally written after
the return statement and will never be executed.
A= Amit
a.replace( A , S ) # this will not work and give error.
You cannot have duplicate keys in dictionary. Also, key should be immutable.
7
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
Ans : There is a module called pdb, which you can use for debugging.
Q44. Which tool you can use, which can help you to find the bugs in your Python source code?
Ans: You can use PyChecker tool, this will help you find the issue with your source code and also help
you to do static analysis for Python.
Q45. Is there any tool or library which I can use to convert my Python code as windows executables or
windows exe?
Ans: You can use py2exe tool, it convert the Python scripts into windows executables or exe and to run it
you don t have to explicitly install the python on your windows machine.
name='Amit'
def fullname():
print name
Reason: This is because when you make an assignment to a variable in a scope, that variable becomes
local to that scope and shadows any similarly named variable in the outer scope. Since the last
statement in fullname assigns a new value to name, the compiler recognizes it as a local variable.
Consequently when the earlier print name attempts to print the uninitialized local variable and an error
results.
def fullname():
global name
print name
name= name+'Khanna'
print name
fullname()
8
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
Q48. I am still confused with the local and global variables of Python?
Ans : If you have defined variable outside the function and only referencing them inside the function is
considered global variable. But if you try to assign them with same or new value then it will be
considered a local variable and local variable must be initialized first to use it else you will get
UnboundLocalError
doubled= []
for v1 in range(5) :
doubled.append(lambda:2*v1)
print(doubled[0](), doubled[1](), doubled[2](), doubled[3]() , doubled[4]())
Ans: Because v1 is not a local variable and it is defined in the outer scope and will be accessed in lambda
function. Hence, when the loop ends, value of the v1 variable will be 4. Hence, all the values in the list
will become 8.
To avoid this, you have to define a new variable that is local to the lambda as below
doubled= []
for v1 in range(5) :
doubled.append(lambda x=v1:2*x)
print(doubled[0](), doubled[1](), doubled[2](), doubled[3]() , doubled[4]())
Now, here x is local variable to lambda, which holds the current value and then doubled and then
appended to list.
Q50. How to make a variable shared across all the modules in your application and it should be
global?
Ans: If you want to make a variable global across all the modules in your application than you have to
define a new module usually config.py and then define that global variable in that module.
Import the config.py module in each of your application module. And as you know, only one instance of
a particular module will be created. Hence, any change you make to global variable in any module will
be reflected in each module. See below example with three different module files
config.py
import config
config.price=2000 #Increase the price to 2000INR and same will be reflected in each module
9
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
course_detail.py
import config
import hadoop
print(config.price)
Ans : Because, if you have created a variable with the same name as defined in import module as well,
then it will overwrite your variable and it will be difficult to debug, what happened to the variable.
Q53. What is the circular import and which form of circular import will not create a problem?
Ans : When you have import statement at the top and uses the import nameofmodule it is fine.
a.py
import b
b.py
import a
This is circular import and they will work fine, without any issue.
a.py
from b import x
b.py
from a import y
Here, module a is busy importing module b and in module b value y from module a is not yet available.
Hence, this kind of circular import should be avoided at the top level and needs to move import to
function or class level.
10
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
Only move imports into a local scope, such as inside a function definition, if it s necessary to solve a
problem such as avoiding a circular import or are trying to reduce the initialization time of a module.
This technique is especially helpful if many of the imports are unnecessary depending on how the
program executes. You may also want to move imports into a function if the modules are only ever used
in that function. Note that loading a module the first time may be expensive because of the one time
initialization of the module, but loading a module multiple times is virtually free, costing only a couple of
dictionary lookups. Even if the module name has gone out of scope, the module is probably available
in sys.modules.
Q55. When you define a function with default shared value like def function_name(mydict={}): what
issue you will see?
def fun1(my_dict={}):
… do so ethi g…
my_dict[key1]= val1
return my_dict
Here, it is expected that every time you call the function fun1, it will create a new my_dict instance with
no values. But this is not correct, because default values are created only once. And any subsequent call
to that function will use the already created my_dict object.
To avoid such scenario, you should have used None as a default value and inside the function you should
check whether the value is None then create a new my_dict.
def fun1(my_dict=None):
if my_dict is None:
my_dict={} #now it is a local dictionary object
Q56. How, can you pass optional or keyword parameters from one function to another function?
Ans: You have to collect the arguments as * and ** , which will give you positional arguments as a tuple
and the keyword arguments as a dictionary. You can pass these arguments when calling another
function using the * and **
list1 = [ ]
list2 = list1
list2.append( hadoopexam.com )
11
What all the values are in list1 and list2?
Ans : Both list1 and list2 will hold the same value. Because, list2 is pointing to the same list as created by
list1. Hence, any modification you do either through list1 or list2 , changes will be reflected in both. In
fact there is only one list and pointed by two variables named list1 and list2.
Ans : Here x will have 101 and y will be 100. Because, integers are immutable and when you do x=x+1 , it
will be creating new int object and variable x will be assigned that variable. However, y will still hold the
old value.
Ans: In this case y will hold the sorted list , but variable x is pointing to None. Most of the cases the
operation which mutate object itself return None. Here, y itself sorted.
x=(1,2,3)
x+=(100,)
Q61. How do you find, if two variables are pointing to the same object or not?
Ans: You should have used is operator or build-in function id().
Q62. How can you return more than 1 value from a function?
Ans : You should have used tuple as a return value. If you want more than 1 value as a return value.
def doOperation(a,b):
12
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
def operation(x):
return (a+x) *(b+x)
return operation
Here, doOperation function take two arguments a and b as input and return operation function as an
output. So you call the function as below.
result=doOperation(5,10)
result(10)
New_list=old_list[:]
Q65. Which method will you use to find all the methods and attributes of an Object of a class?
Ans : We will be using either help() or dir() method.
( x in a ) , x
(False, x )
X=100
Y=20
Ans: Here Val will have 20. Because first condition is false, which will result in Y, which is 20.
Q68. How will you remove the duplicate elements from the list?
Ans: It s very simple, as we know set contain only unique values. Hence, first convert list to set and then
set back to list.
list(set(list_with_duplicates))
13
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
- For module: It will return all the module s attributes and functions.
- For Class object: It will return all the attributes of the same class as well as the base class
attributes.
help() : Help function, name itself defines the usage of this function. This function returns the help
related to python module, object or method if it is called with respective argument but without any
argument it will return the help related to currently running programming module.
Q75. Why Python does not de-allocate all the memory on exits?
Ans: Python does not de-allocate all the memory as soon as it exits, because some memory is reserved
by C library and possible there could be some circular references exists. Hence, memory can not be de-
allocated immediately in Python.
14
Learn Python in less than 8 Hrs (Sitting @ Home/Desk) (Sitting @
Home/Desk)
l1=[1,2,3]
l2=['a','b','c','d']
l3=['hadoop' , 'exam' , 'learning']
zip(l1,l2,l3)
Out[11]:
[(1, 'a', 'hadoop'), (2, 'b', 'exam'), (3, 'c', 'learning')]
It will create tuple only the minimum length of the any list.
If you would leave out the pass, the code wouldn't run. To summarize, the pass statement does nothing
particular but can act as a placeholder.
However, there are many more usage but in short that is.
15
Ans : In python the with keyword is used when working with unmanaged resources (like file streams). It
allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if
exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.
It s handy when you have two related operations which you d like to execute as a pair, with a block of
code in between. The classic example is opening a file, manipulating the file, then closing it:
with open('HadoopExam.txt', 'w') as f:
f.write('Welco e to HadoopExa Lear i g Resources…')
The above with statement will automatically close the file after the nested block of code. (Continue
reading to see exactly how the close occurs.) The advantage of using a with statement is that it is
guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end
of the block, it will close the file before the exception is caught by an outer exception handler. If the
nested block were to contain a return statement, or a continue or break statement, the with statement
would automatically close the file in those cases, too.
Q85. Which is faster when we need to apply search operation on list and dictionary?
Ans : Dictionary will be faster than list, if you search based on the key.
16
Learn Python in less than 8 Hrs (Sitting @ Home/Desk)
Ans : you don't have to invoke it directly. The invocation is realized behind the scenes. When you create
an instance x of a class A with the statement "x = A()", Python will do the necessary calls to __new__ and
__init__.
The answer is simply philosophy. Guido doesn't like hiding things, and many in the Python community
agree with him.
try:
doSomething()
except:
pass
TRAINING'S (AVAILABLE)
17
MapR Spark Developer Certification (In Progress)
Azure 70-532
Azure 70-533
EMC E20-007
EMC E20-007
18
ORACLE JAVA CERTIFICATION (AVAILABLE)
Java 1z0-808
Java 1z0-809
Java 1z0-897 (Java WebService Certification)
Subscribe Here for Regular Updates: Like New Training Module launched
Become Author and Trainer: We are looking for Author (Writing Technical Books) and Trainer (Creating
Training Material): No Compromise on Quality.
Benefit: You will get very good revenue sharing. Please drop us an email to hadoopexam@gmail.com (For the
skills, you feel you are master)
We are sure, you are good at least one technology. Don’t limit your potential, contact us immediately with your
skill. Our expert team will contact you with more detail. You training and Books will reach to all our existing
network and with our expert marketing team we will help you to reach as much as technical professional, with
our Smart Advertising network. Contact us with sending an email hadoopexam@gmail.com
Opportunity to share your knowledge with all learners who are in need. We are helping 1000's of learners since
last 4 years and established ourselves with Quality low cost material.
19