0% found this document useful (0 votes)
60 views20 pages

80 Q and A Data Science

Python is an interpreted, object-oriented programming language that is easy to read and portable. It has simple syntax and built-in data structures. This document provides 80 Python interview questions and answers covering topics like Python basics, data types, functions, OOP concepts, exceptions, and more. The questions are designed to test a candidate's knowledge of Python programming.

Uploaded by

Vikash Rryder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views20 pages

80 Q and A Data Science

Python is an interpreted, object-oriented programming language that is easy to read and portable. It has simple syntax and built-in data structures. This document provides 80 Python interview questions and answers covering topics like Python basics, data types, functions, OOP concepts, exceptions, and more. The questions are designed to test a candidate's knowledge of Python programming.

Uploaded by

Vikash Rryder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Open in app Get started

You have 2 free stories left this month. Sign up and get an extra one for free.

80 Python Interview Practice Questions


Python Questions and Answer Collection from many sources

Cornellius Yudha Wijaya Follow


Jun 23 · 17 min read

Photo by Maxwell Nelson on Unsplash

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 inter view with the Python knowledge. In this case, I tr y to outline
the Python Inter view question I collected from many sources and my own. I tr y to
select the question that most likely would be asked and what is important to know.
Here they are.

. . .

1. W hat is Python?

Python is a programming language with objects, modules, threads, exceptions, and


automatic memor y management. Python is designed to be highly readable. It uses
English keywords frequently whereas other languages use punctuation, and it has
fewer syntactical constructions than other languages.

2. W hat are the benefits of using Python?

The benefits of pythons are that it is simple and easy, portable, extensible, build-in
data structure and it is open-source.

3. How is Python an interpreted language?

An interpreted language is any programming language that is not in machine-level


code before runtime. Therefore, Python is an interpreted language.

4. How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the
source code. It converts the source code that is written by the programmer into an
intermediate language, which is again translated into machine language that has to
be executed.

5. How is memory managed in Python?

Memor y in Python is managed by Python private heap space. All Python objects
and data structures are located in a private heap. This private heap is taken
care of by Python Interpreter itself, and a programmer doesn’t have access to
this private heap.

Python memor y manager takes care of the allocation of Python private heap
space.

Memor y for Python private heap space is made available by Python’s in-built
garbage collector, which recycles and frees up all the unused memor y.

6. W hat 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.

7. How do you write comments in python?

Comments in Python start with a # character.

#Comment Example

8. How to comment on multiple lines in python?

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 ver y good shortcut method to comment on
multiple lines. All you need to do is hold the ctrl key and left-click in ever y 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.

9. W hat are docstrings in Python?

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, ser ve the purpose of comments as well.

"""
This is Docstring example
It is useful for documentation purposes
"""
10. Is indentation optional in Python?

Indentation in Python is compulsor y and is part of its syntax.

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 compulsor y.

11. W hat is a function in Python?

A function is a block of code that is executed only when it is called. To define a


Python function, the def keyword is used. If the function returning something, they
need a return keyword.

def example(a):
return a*2

12. W hat are local variables and global variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables.
These variables can be accessed by any function in the program.

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.

#Example of Global Variable


a = 1

#Example of Local Variable


def sample():
#Local Variable
a = 1

13. W hat is a lambda function?


An anonymous or unnamed function is known as a lambda function. This function
can have any number of parameters but, can have just one statement. It is often
used as a one-time function rather than a function that used repeatedly.

#Example of Lambda Function

test = lambda x,y: x*y


print(test(2,4))

14. W hy lambda forms in python does not have statements?

A lambda form in python does not have statements as it is used to make new
function object and then return them at runtime.

15. W hat are the supported data types in Python?

Python has five standard data types −

Numbers (Integer and Float)

String

List

Tuple

Dictionar y

16. W hat are indexes?

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.

#Example usage of index

list_ex = [1,2, 'Test']


print(list_ex[0])

17. W hat 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 usage of index

list_ex = [1,2, 'Test']


print(list_ex[-1])

18. W hat is a dictionary in Python?

Python dictionar y is one of the supported data types in Python. It is an unordered


collection of elements. The elements in dictionaries are stored as key-value pairs.
Dictionaries are indexed by keys. The data type is presented by {} .

#Example of Dictionary

dictionary = {'key' : 'value'}

19. How to access values in a dictionary?

You could access the values in a dictionar y by indexing using the key. Indexing is
presented by [] .

#Accessing Dictionary

dictionary = {'key' : 'value'}


print(dictionary['key'])

20. How do you get a list of all the keys in a dictionary?

In Dictionar y, there is a keys() attribute we could use.

dictionary = {'key' : 'value', 'key1': : 'value1'}


print(dictionary.keys())
21. W hat is the difference between list and tuple?

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 [] and tuple
defined using () .

#Example of list and tuple

#List
list_ex = [1,2,'test']

#List is mutable
list_ex[0] = 100

#Tuple
tuple_ex = (1,2,'test)

#Tuple is not mutable


tuple_ex[0] = 100 #It would error

22. In Python what are iterators?

In Python, iterators are used to iterate a group of elements, containers like the list
or string. By iteration, it means that it could be looped by using a statement.

23. W hat does [::-1} do?

[::-1] is used to reverse the order of any iterable object.

#Reverse example

string = 'this is a string'


print(string[::-1])

24. How can the ternary operators be used in python?

The Ternar y 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.

#Ternary operators example


a = 1

#The true values


if a < 1:
print('Less')
#If the previous condition haven't fulfilled
else:
print('More')

25. How does break work?

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

26. W hat is the purpose pass statement in python?

The pass statement in Python is used when a statement is required syntactically 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

27. W hat is a map function in Python?

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.

#map function example


def number_exponential(num):
return num**2

number_list = [2,3,4,5]

print(list(map(number_exponential, number_list)))

28. W hat is a enumerate function in python?

The enumerate() method adds a counter to an iterable and returns it in a form of


enumerate object. The object would consist of the counter and the iterable values.

#Enumerate example

iter_example = ['test', 'test2', 'test3']


for idx, val in enumerate(iter_example):
print(idx)
print(val)

29. W hat is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionar y or List based on
existing iterable. It is created by looping inside the Dictionar y or List object.

#Dictionary comprehension

dict_comprehension = {key:val for key, val in emumerate('sample')}


print(dict_comprehension)

#List comprehension

list_comprehension = [i for i in range(5)]


print(list_comprehension)

30. W hat is slicing in Python?

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])

31. W hat are the purposes of not in the operator?


Operators are special functions. They take one or more values and produce a
corresponding result. not would return the inverse of the boolean value.

print(not 1 == 2)

32. W hat is the purpose of // in python?

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)

33. How do you add a new value to a list object?

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.

list_example = [1,2,3,4,5]
list_example.append(6)
print(list_example)

34. W hat is a shallow copy?

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.

#Example of shallow copy

list_example = [1,2,3,4,5]
another_list = list_example
another_list[0] = 100
print(list_example)

35. W hat is a deep copy?

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.

#Example of Deep copy

list_example = [1,2,3,4,5]

#Iniating Deep copy with .copy attribute


another_list = list_example.copy()
another_list[0] = 100
print(list_example)

36. How to create an empty class in Python?

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
executed. it’s a null statement.

class sample:
pass
test=sample()
test.name="test1"
print(test.name)

37. W hat is self-keyword in Python?

Self-keyword is used as the first parameter of a function inside a class that


represents the instance of the class. The object or the instance of the class is
automatically passed to the method that it belongs to and is received in the ‘self-
keyword.’ Users can use another name for the first parameter of the function that
catches the object of the class, but it is recommended to use ‘self-keyword’ as it is
more of a Python convention.

38. W ill 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++.

39. How will you convert a list into a string?

In this case, we could use a .join() attribute from the string object. Here we passed
the list object to the attribute.

list_example = ['apple', 'grape', 'orange']


print(' '.join(list_example))

40. W hat is a membership operator?

It is an operator that can confirm if a value is a member in another object. The


operators are ‘in’ and ‘not in’

#Example membership operators

print('me' in 'membership')
print('mes' not in 'membership')

41. W hat is identity operators in Python?

Identity operators is an operator that tell us if two values have the same identity.
The operators are ‘is’ and ‘is not’.

#Example Identity operators


print(1 is '1')
print(2 is not '2')

42. How do you take input in Python?


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.

test = input('input a number: ')


print(test)

43. W hat does the function zip() do?

It would return an iterator of tuples. It would form an n-pair of value from iterable
passed on the function. The n is the number of iterable passed on the function.

#Zip function example

print(list(zip([1,2,3], ['apple', 'grape', 'orange'], ['x', 2,


True])))

for num, fruit, thing in zip([1,2,3], ['apple', 'grape', 'orange'],


['x', 2, True]):
print(num)
print(fruit)
print(thing)

44. W hat 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.

for i in range(5):
print(i)

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. W hat is the best code you can write to swap two numbers?

You can perform the swab with a single line of code.

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

47. How to break out of the Infinite loop?

You can do it by pressing Ctrl+C to interrupt the looping process.

48. W hat is the with statement in Python?

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.

#Example of with statement

with open('database.txt') as data:


print(data)

49. In a try-except block, when is except block executed?

The tr y-except block is commonly used when we want something to execute when
errors were raised. The except block is executed when the code in the tr y block has
encountered an error.

a = (1,2,3)
try:
a[0] = 2
except:
print('There is an error')

50. W here will you use while rather than for ?

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.

51. W hat is a Python module?

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 not only help in
keeping Python codes organized but also in making codes less complex and more
efficient.

import #name of the module

52. W hat is PYTHONPATH?


It is an environment variable that is used when a module is imported. Whenever a
module is imported, PYTHONPATH is also looked up to check for the existence of the
imported modules in various directories. The interpreter uses it to determine which
module to load.

53. Name the example of file-processing modes with Python?

We have the following modes:

Read-only mode(‘r’): Open a file for reading. It is the default mode.

Write-only mode(‘w’): Open a file for writing. If the file contains data, data
would be lost. Another new file is created.

Read-Write mode(‘r w’): Open a file for reading, write mode. It means updating
mode.

Append mode(‘a’): Open for writing, append to the end of the file, if the file
exists.

54. W hat is pickling and unpickling?

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
file = pickle.load(open('file.sav', 'rb'))

55. Is python NumPy array better than lists?

We use python NumPy array instead of a list because of the below three reasons:

1. Less Memor y
2. Fast

3. Convenient

56. How do you calculate percentiles with NumPy?

Percentiles is the position of the ordered number in a certain percentile. We can


calculate the percentile with NumPy using the following code.

import numpy as np

a = np.array([i for i in range(100)])


p = np.percentile(a, 50) #Returns 50th percentile, e.g. median

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 director y we’re presently working under, we can use the getcwd()
method from the os module.

import os
os.getcwd()

58. W hat do you see below? W hat would happen if we execute it?

a = '1'
b = '2'
c = '3'

s = a + ‘[‘ + b + ‘:’ + c + ‘]’


print(s)

This is string concatenation. If even one of the variables isn’t a string, this would
raise a TypeError. What would happen is that we get an output of the string
concatenation.

59. How would you randomize the contents of a list in-place?


We can use the help of function shuffle() from the module random.

from random import shuffle


list_example = [1,2,3,4,5,6,7,8]
shuffle(list_example)

60. W hat is a cast in Python?

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)

61. Explain why are we getting an error here?

from numpy imprt stdev

ImportError Traceback (most recent call last)


<ipython-input-26-685c12521ed4> in <module>
----> 1 from numpy import stdev

ImportError: cannot import name 'stdev' from 'numpy'

In the above code, we tr y to import a non-exist function from the numpy module.
That is why we getting an error.

62. How can you unsign or delete variables in Python?

We could use the del() function to remove or unsign a variable. This is considered a
good practice to remove all the unnecessar y variables when we are not using it.

a = 1
del a

63. W hat is a pandas in Python?


pandas is a Python package providing fast, flexible, and expressive data structures
designed to make working with “relational” or “labeled” data both easy and
intuitive. It aims to be the fundamental high-level building block for doing practical,
real-world data analysis in Python.

64. W hat is the difference between append() and extend() methods?

Both append() and extend() methods are methods used to add elements at the end
of a list.

append(element): Adds the given element at the end of the list

extend(another-list): Adds the elements of another list at the end of the list

65. How do you find the current version of Python?

We can find our Python current version by using sys.version.

import sys
sys.version

66. W hat 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 dictionar y 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)

#Example of **kwargs
def sample(**kwargs):
print(kwargs)

sample(a = 'time', b = 1)
67. W hat is help() and dir() functions in Python?

The help() function displays the documentation string and helps for its argument.

import numpy
help(numpy.array)

The dir() function displays all the members of an object(any kind).

import numpy
dir(numpy.array)

68. W hat is the meaning of a single- and a double-underscore before an object


name?

Single Underscore — Names, in a class, with a leading underscore are simply to


indicate to other programmers that the attribute or method is intended to be
private. However, nothing special is done with the name itself.

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.

69. W hat is the output of this below query?

ss = “Python Programming!”
print(ss[5])

The answer is ‘n’

70. W rite a program in Python to produce a Star triangle.

You might also like