Python Mock Questions
Python Mock Questions
You have 1 free member-only story left this month. Sign up for Medium and get an extra one
Many Data Aspirant started learning their Data Science journey with Python
Programming Language. Why Python? because it was easy to follow and many
companies use Python programming language these days. Moreover, Python is a
multi-purpose language that not specific only for Data scientists; people also use
Python for developer purposes.
When you applying for a position as a Data Scientist, many companies would
need you to follow a job interview with the Python knowledge. In this case, I try
to outline the Python Interview question I collected from many sources and my
own. I try to select the question that most likely would be asked and what is
important to know. Here they are.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 1/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
1. What is Python?
The benefits of pythons are that it is simple and easy, portable, extensible, build-
in data structure and it is open-source.
Python memory manager takes care of the allocation of Python private heap
space.
Memory for Python private heap space is made available by Python’s in-built
garbage collector, which recycles and frees up all the unused memory.
6. What is pep 8?
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how
to format Python code for maximum readability.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 2/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
#Comment Example
Multi-line comments appear in more than one line. All the lines to be commented
are to be prefixed by a #. You can also a very good shortcut method to comment
on multiple lines. All you need to do is hold the ctrl key and left-click in every
place wherever you want to include a # character and type a # just once. This
will comment on all the lines where you introduced your cursor.
Docstrings are not actually comments, but, they are documentation strings. These
docstrings are within triple quotes. They are not assigned to any variable and
therefore, at times, serve the purpose of comments as well.
"""
This is Docstring example
It is useful for documentation purposes
"""
All programming languages have some way of defining the scope and extent of
the block of codes; in Python, it is indentation. Indentation provides better
readability to the code, which is probably why Python has made it compulsory.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 3/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
def example(a):
return a*2 Sign In Get started
Global Variables:
Local Variables:
Any variable declared inside a function is known as a local variable. This variable
is present in the local space and not in the global space.
A lambda form in python does not have statements as it is used to make new
function object and then return them at runtime.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 4/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
String
List
Tuple
Dictionary
To access an element from ordered sequences, we simply use the index of the
element, which is the position number of that particular element. The index
usually starts from 0, i.e., the first element has index 0, the second has 1, and so
on.
17. What are negative indexes and why are they used?
When we use the index to access elements from the end of a list, it’s called
reverse indexing. In reverse indexing, the indexing of elements starts from the
last element with the index number −1. The second last element has index ‘−2’,
and so on. These indexes used in reverse indexing are called negative indexes.
#Example of Dictionary
You could access the values in a dictionary by indexing using the key. Indexing is
presented by [] .
#Accessing Dictionary
The difference between list and tuple is that list is mutable while tuple is not.
Tuple can be hashed for e.g as a key for dictionaries. The list is defined using []
#List
list_ex = [1,2,'test']
#List is mutable
list_ex[0] = 100
#Tuple
tuple_ex = (1,2,'test)
In Python, iterators are used to iterate a group of elements, containers like the
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 6/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
y g p
list or string. By iteration, it means that it could be looped by using a statement.
Sign In Get started
#Reverse example
The Ternary operator is the operator that is used to show the conditional
statements. This consists of true or false values with a statement that has to be
evaluated for it.
a = 1
The break statement allows loop termination when some condition is met and
the control is transferred to the next statement.
#Break example
for i in range(5):
if i < 3:
print(i)
else:
break
Th t t t i P th i d h t t ti i d t ti ll
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 7/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
The pass statement in Python is used when a statement is required syntactically
Sign In Get started
but you do not want any command or code to execute.
#Pass example
for i in range(10):
if i%2 == 0:
print(i)
else:
pass
The map() function is a function that takes a function as an argument and then
applies that function to all the elements of an iterable, passed to it as another
argument. It would return a map object so we need to transform it to a list object.
def number_exponential(num):
return num**2
number_list = [2,3,4,5]
print(list(map(number_exponential, number_list)))
#Enumerate example
They are syntax constructions to ease the creation of a Dictionary or List based
on existing iterable. It is created by looping inside the Dictionary or List object.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 8/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
#List comprehension
Slicing is a mechanism to select a range of items from sequence types like list,
tuple, strings, etc. This slicing is done by indexing method.
#Slicing example
list_example = [1,2,3,4,'test','test2']
print(list_example[1:4])
print(not 1 == 2)
It is a Floor Division operator, which is used for dividing two operands with the
result showing only digits before the decimal point.
print(5//2)
You can do it by using .append() attribute that list has. By passing any values to
the .append() attribute, the new value would be placed at the end of the list
sequence.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 9/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
list_example = [1,2,3,4,5]
list_example.append(6)
print(list_example)
Shallow copy is used when a new instance type gets created and it keeps the
values that are copied in the new instance. Shallow copy is used to copy the
reference pointers just like it copies the values. It means when we copying an
object to another variable, it would be connected.
list_example = [1,2,3,4,5]
another_list = list_example
another_list[0] = 100
print(list_example)
Deep copy is used to store the values that are already copied. The deep copy
doesn’t copy the reference pointers to the objects. It makes the reference to an
object and the new object that is pointed by some other object gets stored.
Contrast with a shallow copy, The changes made in the original copy won’t affect
any other copy that uses the object. It means they are not connected.
list_example = [1,2,3,4,5]
An empty class is a class that does not have any code defined within its block. It
can be created using the pass keyword. However, you can create objects of this
class outside the class itself. In Python, the pass command does nothing when its
t d it’ ll t t t
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 10/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
executed. it’s a null statement.
Sign In Get started
class sample:
pass
test=sample()
test.name="test1"
print(test.name)
38. Will the do-while loop work if you don’t end it with a semicolon?
This is a Trick question! Python does not support an intrinsic do-while loop.
Secondly, to terminate do-while loops is a necessity for languages like C++.
In this case, we could use a .join() attribute from the string object. Here we
passed the list object to the attribute.
print('me' in 'membership')
print('mes' not in 'membership')
Identity operators is an operator that tell us if two values have the same identity.
The operators are ‘is’ and ‘is not’.
For taking input from the user, we could use the function input(). This function
would take input from the user and return the input into a string object.
44. What is the difference if range() function takes one argument, two
arguments, and three arguments?
When we pass only one argument, it takes it as the stop value. Here, the start
value is 0, and the step value is +1. The iteration with a range would always stop
1 value before the stop value.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 12/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
When we pass two arguments, the first one is the start value, and the second is
the stop value.
for i in range(1,5):
print(i)
Using three arguments, the first argument is the start value, the second is the
stop value, and the third is the step value.
for i in range(1,10,2):
print(i)
45. What is the best code you can write to swap two numbers?
a = 1
b = 2
#Swab number
a, b = b, a
46. How can you declare multiple assignments in one line of code?
There are two ways to do this. First is by separately declare the variable in the
same line.
a, b, c = 1,2,3
Another way is by declaring the variable in the same line with only one value.
a=b=c=1
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 13/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
47. How to break out of the Infinite loop? Sign In Get started
The with statement in Python ensures that cleanup code is executed when
working with unmanaged resources by encapsulating common preparation and
cleanup tasks. It may be used to open a file, do something, and then
automatically close the file at the end. It may be used to open a database
connection, do some processing, then automatically close the connection to
ensure resources are closed and available for others. with will cleanup the
resources even if an exception is thrown.
a = (1,2,3)
try:
a[0] = 2
except:
print('There is an error')
For simple repetitive looping and when we don’t need to iterate through a list of
items- like database records and characters in a string.
Modules are independent Python scripts with the .py extension that can be
reused in other Python codes or scripts using the import statement. A module
can consist of functions, classes, and variables, or some runnable code. Modules
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 14/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
not only help in keeping Python codes organized but also in making codes less
complex and more efficient.
Write-only mode(‘w’): Open a file for writing. If the file contains data, data
would be lost. Another new file is created.
Append mode(‘a’): Open for writing, append to the end of the file, if the file
exists.
Pickle module accepts any Python object and converts it into a string
representation and dumps it into a file by using a dump function, this process is
called pickling. While the process of retrieving original Python objects from the
stored string representation is called unpickling.
import pickle
a = 1
#Pickling process
pickle.dump(a, open('file.sav', 'wb'))
#Unpickling process
i i i
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 15/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
file = pickle.load(open('file.sav', 'rb'))
Sign In Get started
We use python NumPy array instead of a list because of the below three reasons:
1. Less Memory
2. Fast
3. Convenient
import numpy as np
print(p)
57. How do you get the current working directory using Python?
Working with Python, you may need to read and write files from various
directories. To find out which directory we’re presently working under, we can
use the getcwd() method from the os module.
import os
os.getcwd()
58. What do you see below? What would happen if we execute it?
a = '1'
b = '2'
c = '3'
hi i i i f f h
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac
i bl i ’ i hi ld 16/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
This is string concatenation. If even one of the variables isn’t a string, this would
Sign In Get started
raise a TypeError. What would happen is that we get an output of the string
concatenation.
We can use the help of function shuffle() from the module random.
Casting is when we convert a variable value from one type to another. In Python,
it could be done with functions such as list(),int(), float() or str() . An example is
when you convert a string into an integer object.
a = '1'
b = int(a)
In the above code, we try to import a non-exist function from the numpy module.
That is why we getting an error.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 17/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
a = 1
Sign In Get started
del a
Both append() and extend() methods are methods used to add elements at the
end of a list.
extend(another-list): Adds the elements of another list at the end of the list
import sys
sys.version
66. What does this mean: *args, **kwargs? And why would we use it?
We use *args when we aren’t sure how many arguments are going to be passed to
a function, or if we want to pass a stored list or tuple of arguments to a function.
**kwargs is used when we don’t know how many keyword arguments will be
passed to a function, or it can be used to pass the values of a dictionary as
keyword arguments. The identifiers args and kwargs are optional, as you could
change it to another name such as *example **another but it is better to just use
the default name.
#Example of *args
def sample(*args):
print(args)
sample('time', 1, True)
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 18/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
sample(a = 'time', b = 1)
The help() function displays the documentation string and helps for its
argument.
import numpy
help(numpy.array)
348 3
import numpy
dir(numpy.array)
Double Underscore (Name Mangling) — Any identifier of the form __spam (at
least two leading underscores, at most one trailing underscore) is textually
replaced with _classname__spam, where the class name is the current class
name with a leading underscore(s) stripped. This mangling is done without
regard to the syntactic position of the identifier, so it can be used to define class-
private instance and class variables, methods, variables stored in globals, and
even variables stored in instances. private to this class on instances of other
classes.
ss = “Python Programming!”
print(ss[5])
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 19/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
def star_triangle(r):
for x in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
star_triangle(7)
counter = 0
def increment():
counter += 1
increment()
Python doesn’t have variable declarations, so it has to figure out the scope of
variables itself. If there is an invitation to a variable inside a function, that
variable is considered local. The counter variable above is a global variable and
thus, the line of code above would raise an error.
We can use the .split() attribute from the string. It takes the separator as an
argument and return list consisting of splitting results of the string based on the
separator.
if a==b:
print("palindrome")
else:
print("Not a Palindrome")
def squares(n):
i=1
while(i<=n):
yield i**2
i+=1
for i in squares(7):
print(i)
a=int(input("enter a number"))
if a>1:
for x in range(2,a):
if(a%x)==0:
print("not prime")
break
else:
print("Prime")
else:
print("not prime")
76. What is the purpose of the single underscore (‘_’) variable in Python?
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 21/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
Single Inheritance
Multi-level Inheritance
Hierarchical Inheritance
Multiple Inheritance
Tuple unpacking is a process of unpacking the values in the tuple and input it
into a few different variables.
tup = (1,2,3)
A function that doesn’t return anything returns a None object. Not necessarily
does the return keyword mark the end of a function; it merely ends it when
present in the function. Normally, a block of code marks a function, and where it
ends, the function body ends.
Source
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 22/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
Top 100 Python Interview Questions & Answers For 2020 | Edureka Sign In Get started
is the most sought-after skill in programming domain. In this Python
Interview Questions blog, I will introduce you to…
www.edureka.co
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 23/24
8/27/22, 11:09 AM 80 Python Interview Practice Questions | by Cornellius Yudha Wijaya | Towards Data Science
Every Thursday, the Variable delivers the very best of Towards Data Science: from hands-on tutorials and cutting-edge
research to original features you don't want to miss. Take a look.
By signing up, you will create a Medium account if you don’t already have one. Review Get this newsletter
our Privacy Policy for more information about our privacy practices.
https://towardsdatascience.com/80-python-interview-practice-questions-f1640eea66ac 24/24