Top ANswers to Data Science Interview Question

By Codegnan | 3987 Views | 10 Mins Read | Updated on March 10, 2020

This blog contains the review of common interview questions and answers that are asked during a Data Science interview. You’ll get to know how to answer basic data science interview questions related to predictions, underfitting, and overfitting. Also, with 80 Data Science interview questions, you will walk through the typical questions related to statistics and probability and some more related to data structures and algorithms. The technical skills required to appear for the interview are: o Python o SQL o Statistics and Probability o Algorithms o Supervised and Unsupervised Machine Learning

Q1) What is Python?

Python is a high-level, interpreted, and general-purpose programming language. General-purpose language means it can be used to create almost any type of application with the right tools or libraries. Python supports objects, modules, threads, exception-handling and automatic memory management which helps in modeling real-world problems and creating applications to solve these problems.

Q2) Explain the key features of Python

1.Deciphered language: Python is a deciphered language which implies that, dissimilar to programming languages like C and its variations, Python shouldn't be compiled before it is run. Other deciphered dialects are PHP and Ruby. 
2.Dynamically typed language: Python is dynamically typed language this implies you don't have to express the sorts of factors when you pronounce them or anything like that. You can do things like x=111 and afterward x="it is a string" without error. 
3.Object oriented programming approach: Python is appropriate to object oriented programming as it permits the meaning of classes alongside creation and inheritance. Python doesn't approach specifiers (like C++'s public, private). 
4.Functional language: In Python, functions are top of the line objects. This implies they can be allocated to variables, returned from different functions and can be passed to functions. Classes are also known as  top of the line objects 
5.Quick compose of coding: Composing Python code is quick however running it is regularly slower than other programming languages. Fortunately Python permits the incorporation of C based extensions so bottlenecks can be improved. The NumPy package is a genuine case of this present, it is actually very fast in light of the fact that a great deal of the calculating it does isn't really done by Python 
6.Global use: Python can be used globally – web applications, automation, scientific modeling, big data applications and some more. 

Q3) Why is Python called a dynamically typed language?

Typing means type-checking in programming languages. Python is a strongly typed language which means "1" + 2 will result in a type error, since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other side, a weakly-typed  language like Javascript, will simply output "12" as a result.

Type-checking can be done at two stages -

Static - Data Types are checked before execution.

Dynamic - Data Types are checked during execution.

Python is known as an interpreted language as it executes each statement line by line and thus type-checking is done on the fly, during execution. By this means, Python is a Dynamically Typed language.

Q4) What are Python namespaces?

Namespaces in Python are known as dictionaries with “name as key” mapped to a corresponding “object as value”. This allows multiple namespaces to utilize the same name and map it to a separate object. Following are the types of namespaces used in Python:

Local Namespace that includes local names inside a function. It is temporarily created for a function call and gets cleared when the function returns.

Global Namespace that includes names from various imported packages or modules that are being used in the current project. It is created when the package is imported in the script and lasts until the execution of the script.

Built-in Namespace that includes built-in functions of core Python and built-in names for various types of exceptions.

Q5) Explain the scope of an object in Python?

Local: It refers to the local objects available in the current function.

Global: It refers to the objects available throughout the code execution since their inception.

Module-level: It refers to the global objects of the current module accessible in the program.

Outermost: It refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

Tip: Local scope objects can be synced with global scope objects using keywords such as global.

Q6) State definition and differences between lists and tuples in Python?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['John’, 6, 0.19], while tuples are represented with parentheses ('Sena', 5, 0.97).

my_tuple = ('John', 6, 5, 0.97)

my_list = ['John', 6, 5, 0.97]

print(my_tuple[0])     # output => 'John'

print(my_list[0])     # output => 'John'

my_tuple[0] = 'Sena'    # modifying tuple => throws an error

my_list[0] = 'Sena'    # modifying list => list modified

print(my_tuple[0])     # output => 'John'

print(my_list[0])     # output => 'Sena'

Q7) How to check if all characters in a string are alphanumeric?

For this, we use the method isalnum()

Q8) What are the different methods to capitalize the first letter of a string in Python?

By using the method capitalize().

>>> 'abc'.capitalize()

‘ABC’

 

Or

>>> type(str.capitalize)

 

However, it will let other characters be.

>>> '@bc'.capitalize()

‘@bc’

Or

>>> 'abc123'.isalnum()

 

Other methods that we have include:

>>> '123'.isnumeric()

or

>>> 'abc'.islower()

            or

>>> 'Abc'.istitle()

Or       

>>> ' '.isspace()

Q9) What are the disadvantages of using Python?

1.Design restrictions
2.Slow when compared to C/C++ or Java
3.Weak in mobile computing
4.Underdeveloped database access layers

Q10) How will you find which directory you are currently in?

With the use of a function named getcwd(). It is used by importing it from the module OS.

For example:

>>> import os

>>> os.getcwd()

Or

>>> type(os.getcwd)

Or

Simply change the directly we are currently using-

>>> os.chdir('C:\\Users\\mypc\\Desktop')

>>> os.getcwd()

Q11) How can you insert an object at a given index in Python?

Firstly, create a list

>>> ab=[1,2,4]

Then use the method insert. The first argument is the index at which to insert, the second is the value to insert

>>> ab.insert(2,3)

>>> ab

Q12) How can you reverse a list in Python?

Using reverse() method

>>> a.reverse()

>>> a

Or using a slicing method from right to left

>>> a[::-1]

>>> a

Q13) What is a Python interpreter?

>>> This sign is known as a Python interpreter.

Q14) How does a function return values?

A function uses the ‘return’ keyword to return a value.

>>> def add(a,b):

return a+b

Q15) How can you define a block in Python?

For any kind of statements, we possibly need to define a block of code under them. However, Python does not support curly braces. This means we must end such statements with colons and then indent the blocks under those with the same amount.

>>> if 3>1:

print("Hello")

print("Good day")

Q16) What is the use of break and continue statements in Python?

Both break and continue statements are the control flow statements in Python loops. Break statement stops the current loop from executing further and transfers the control to the next block. Continue statement jumps to the next iteration of the loop without exhausting it.

Q17) Do we need do-while loop work if you don’t end it with a semicolon?

Python does not support an intrinsic do-while loop.

Q18) How you’ll get the max alphabetical character from a string?

With the use of max() method

>>> max('flyiNg')

Q19) What are the applications of Python?

Python can be used in the following:
1.Web and Internet Development
2.Desktop GUI
3.Scientific and Numeric Applications
4.Software Development Applications
5.Applications in Education
6.Applications in Business
7.Database Access
8.Network Programming
9.Games, 3D Graphics
10.And much more…

Q20) State any 10 built-in functions in Python.

1.complex()- Creates a complex number.
>>> complex(3.5,4)
2.eval()- Parses a string as an expression.
>>> eval('print(max(22,22.0)-min(2,3))')
3.filter()- Filters in items for which the condition is true.
>>> list(filter(lambda x:x%2==0,[1,2,0,False]))
4.format()- Format a string
>>> print("a={0} but b={1}".format(a,b))
5.hash()- Returns the hash value of an object.
>>> hash(3.7)
6.hex()- Converts an integer to a hexadecimal.
>>> hex(14)
7.input()- Reads and returns a line of string.
>>> input('Enter a number')
8.len()- Returns the length of an object.
>>> len('Ayushi')
9.locals()- Returns a dictionary of the current local symbol table.
>>> locals()
10.open()- Opens a file.
>>> file=open('tabs.txt')

Q21) What will be the output of this code

>>> word=’abcdefghij’

>>> word[:3]+word[3:]

The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.

Q22) How can you convert a list into a string?

By using join() method

For example:

>>> nums=['one','two','three','four','five','six','seven']

>>> a=' '.join(nums)

>>> a

Q23) How can you remove a duplicate element from a list?

By turning elements into a set

For example:

>>> list=[1,2,1,3,4,2]

>>> set(list)

Q24) What is a Python dictionary?

The Python dictionary holds key-value pairs. It is mutable and uses a comprehension to create it.

Q25) What are membership operators?

With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.

>>> 'me' in 'disappointment'

True

>>> 'us' not in 'disappointment'

True

Q26) What are identity operators in Python?

The operators ‘is’ and ‘is not’ tell us if two values have the same identity.

>>> 10 is '10'

False

>>> True is not False

True

Q27) Explain data types supported by Python.

There are a total of 5 data types supported by Python:
1.Numbers – Numbers are used to hold numerical values.
>>> a=7.0
>>>
2.Strings – A string is a sequence of characters. We declare it using single or double quotes.
>>> title="Aryan's Book"
3.Lists – A list is an ordered collection of values, and we declare it using square brackets.
>>> colors=['red','green','blue']
>>> type(colors)
4.Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, it is that a tuple is immutable. This means that we cannot change a value in it.
>>> name=('Good','day')
>>> name[0]='Avery'
5.Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly braces. 
>>> squares={1:1,2:4,3:9,4:16,5:25}
>>> type(squares)

 We can also use a dictionary comprehension
>>> squares={x:x**2 for x in range(1,6)}
>>> squares

Q28) How can we convert string into an int?

If a string contains only numeric characters, you can convert it into an integer using the int() function.

>>> int('117')

117

Do this to check the types:

>>> type('117')

Or

>>> type(int('117'))

Q29) Explain function in Python.

When we want to execute a sequence of statements, we can give it a name. Let’s define a function to take two numbers and return the greater number.

>>> def greater(a,b):

return a is a>b else b

>>> greater(3,3.5)

Q30) Explain recursion.

When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid forming an infinite loop, we must have a base condition.

For example:

>>> def fact(n):

if n==1: return 1

return n*fact(n-1)

>>> fact(4)

Q31) How can you get all values from a Python dictionary?

To get all the keys from a dictionary, keys() method is used.

>>> 'd' in {'a':1,'b':2,'c':3,'d':4}.values()

Q32) How can you use a toggle case in Python?

By using swapcase() method from the str class

>>> 'HelloWorld'.swapcase()

Q33) You have a string “I Love Python”. Write a code to print upto letter t.

>>> i=0

>>> while s[i]!='t':

print(s[i],end=’’)

i+=1

Q34) You have a string “I Love Python”. Write a code to print everything excerpt the spaces.

>>> for i in s:

if i==' ': continue

print(i,end='')

Q35) You have a string “I Love Python”. Write a code to print this string 5 times in a row

>>> for i in range(6):

print(s)

Q36) What is a control flow statement in Python?

A Python program typically begins to execute from the first line. From that point, it travels through every statement only a single time and when it's finished with the last statement, it exchanges the program. However, we might need to take an increasingly turned path through the code. Control flow statements let us upset the ordinary execution flow of a program and curve it to our will. 

Q37) How can you swap two numbers?

>>> a,b=2,3

>>> a,b=b,a

>>> a,b

Q38) If you are stuck in an infinite loop then how will you break out of it?

Pressing Ctrl+C key combination interrupts the execution.

Q39) How does an infinite loop occur?

>>> def counterfunc(n):

while(n==9):print(n)

>>> counterfunc(9)

Q40) What makes Python an object-oriented language?

In Python, we have the following object-oriented features:
1.Encapsulation
2.Abstraction
3.Inheritance
4..Polymorphism
5.Data hiding

Q41) What type of objects does Python support?

Mutable objects

These let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower.

>>> [2,4,9]

Immutable objects

These do not let us modify their contents. Examples of these will be tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster

>>> tuple=(1,2,4)

>>> tuple

Q42) What are the advantages of using Python?

1.Interpreted
2.Free and open source
3.Extensible
4.Object-oriented
5.Built-in data structure
6.Readability
7.High-Level Language
8.Cross-platform
9.Interpreted
10.Free and open source
11.Portable
12.Extensible
13.Object-oriented
14.Built-in data structure

Q43) What is a zip() function in Python?

Zip() function in Python returns a zip object which maps a similar index of multiple containers.

Syntax:

 zip(iterator1, iterator2, iterator3 ...)

Q44) What is Python’s parameter passing mechanism?

1.Pass by value
2.Pass by reference

Q45) How can you remove whitespaces from a string?

string = "  hello " 

string2 = "    hello        " 

string3 = "       hello" 

print(string) 

print(string2) 

print(string3) 

print("After stripping all have placed in a sequence:") 

print(string.strip()) 

print(string2.strip()) 

print(string3.strip())     

Q46) What are the file processing models supported by Python?

1.Read-only mode : Open a file for reading. It is the default mode.
2.Write-only mode: Open a file for writing. If the file contains data, data would be lost. Another new file is created.
3.Read-Write mode: Open a file for reading, write mode. It means updating mode.
4.Append mode: Open for writing, append to the end of the file, if the file exists.

Q47) What operators Python support?

1.Arithmetic Operators
2.Relational Operators
3.Assignment Operators
4.Logical Operators
5.Membership Operators
6.Identity Operators
7.Bitwise Operators 

Q48) What are Python decorators?

Decorators are very powerful and a useful tool in Python that allows the programmers to modify the behavior of any class or function. It allows us to wrap another function to extend the behavior of the wrapped function, without permanently modifying it.

# Decorator example 

def decoratorfun(): 

    return another_fun  

Q49) In Python, what is pickling and unpickling?

The Python pickle is characterized as a module which acknowledges any Python item and changes over it into a string portrayal. It dumps the Python object into a record utilizing the landfill work; this procedure is called pickling.

The way toward recovering the first Python objects from the put away string representation is called Unpickling. 

Q50) What are the most used looping statements in Python?

For loop and while loop

Q51) What are Python modules?

Module is defined as a file that includes a set of various functions and Python statements that we want to add in our application.

Q52) What is the difference between .py and .pyc files?

.py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python compiler

Q53) Write a code to draw the following triangle.

def pyfun(r):

for a in range(r):

print(' '*(r-x-1)+'*'*(2*x+1)) 

pyfun(9)

Q54) State the difference between NumPy and SciPy.

NumPy

It is a Numerical Python that is used to perform general and efficient calculations on numerical data that is saved in arrays like indexing, reshaping, sorting, etc. It is majorly used to solve linear algebraic functions.

SciPy

It is a Scientific Python that is a collection of tools that is used to perform various operations like differentiation, integration, etc. It is majorly used to solve algebraic calculations.

Q55) How to write multi-line comment in Python

If you want to add multiple comments, you have to insert ‘#’ for each line.

For example:

#This is a comment

#written in

#more than just one line

print("Hello, World!")

or

 """

This is a comment

written in

more than just one line

"""

print("Hello, World!")

Q56) What is Django and list some features.

Django is an advanced-level framework that supports agile growth and clean pragmatic design that is majorly utilized for web development.
Features of Django:
1.Excellent documentation
2.Python web framework
3.SEO optimized
4.High scalability
5.Versatile in nature
6.Offers high security
7.Thoroughly tested
8.Provides rapid Development

Q57) What common security issues are handled by Django?

1.Clickjacking
2.Cross-site scripting and
3.SQL injection

Q58) What are the mandatory files for a Django project?

1.manage.py
2.settings.py
3.__init__.py
4.urls.py
5.wsgi.py

Q59) Name some commonly used modules in Python.

A Python module is a .py file that contains executable code. The most commonly used Python modules are:
1.os
2.sys
3.math
4.random
5.data time
6.JSON

Q60) What is a Lambda function?

Anonymous function is called a Lambda function in Python. Lambda function has a number of parameters but has a single statement.

For example:

a = lambda x,y : x+y

print(a(5, 6))

Q61) Explain docstrings in Python

Docstrings are actually documentation strings that are written within triple quotes. These are not assigned on any variable and are used as general comments too.

For example:

"""

Using docstring as a comment.

This code divides 2 numbers

"""

x=8

y=4

z=x/y

print(z)

Q62)How can you add values in an array?

In Python, elements can be added using various functions like append(), extend(), and insert(i,x)

a=arr.array('d', [1.1 , 2.1 ,3.1] )

a.append(3.4)

print(a)

a.extend([4.5,6.3,6.8])

print(a)

a.insert(2,3.8)

print(a)

Q63) Types of inheritance used in Python

There are 4 types of inheritance are used in Python:
i.Single inheritance
ii.Multi-level inheritance
iii.Hierarchical inheritance
iv.Multiple inheritance


Q64) How can you create a class in Python?

By using a class keyword

class School:

def __init__(self, name):

self.name = name

S1=School("abc")

print(S1.name)

Q65)How can you request a database in Flask?

1.before_request(): Using this we can request a database before only without passing arguments.
2.after_request(): This method is called after requesting the database and also sends the response to the client.
3.teardown_request(): This method is called in the cases where the responses are not guaranteed and the exception is raised. They have no access to modify the request.

Q66) Explain the term monkey patching in Python.

The term monkey patching refers to the dynamic modifications of a class or a module during run-time.

For example:

import m

def monkey_f(self):

print "monkey_f()"

 

m.MyClass.f = monkey_f

obj = m.MyClass()

obj.f()

Q67)How can you create an empty class in Python?

When a class doesn’t have any code within its block, is known as the empty class. To create an empty class, the pass keyword is used.

class a:

    pass

obj=a()

obj.name="xyz"

print("Name = ",obj.name)

Q68) Write a program to check if the entered series is Palindrome or not.

a=input("enter sequence")

b=a[::-1]

if a==b:

    print("palindrome")

else:

    print("Not a Palindrome")

Q69) State reasons to use Python NumPy instead of a list.

Following are the reasons:
1.Less memory
2.Fast
3.Convenient

Q70) Write a program to check the memory usage of an object.

import sys

x = 10

print(sys.getsizeof(x))

Final Words

There are thousands of vacancies available for Python developers and Python experts are expected to be acquainted with the components of Python technologies. With the knowledge of how to use Python during interviews can help you understand the deepness of Python programming that will pay dividends during day-to-day development. Python knowledge is essential for the students and learners to get great employment opportunities in the future. The knowledge of every small detail about Python is the great approach to solve the problems linked with real-time scenarios. A magical trick here is to read and re-read the questions and their answers to get accustomed to what you will be asked in the Python interview. Let these questions be your gateway to your next job as a Python expert.

Talk to our Student Counsellor and choose RIght Career

Our Popular Courses

Online / Classroom

Python Certification

189 Learners

(78)
Get certified from

Online / Classroom

Data Analysis Certification

189 Learners

(78)
Get certified from

Online / Classroom

Data Science Certification

189 Learners

(78)
Get certified from

Online / Classroom

Computer Vision Certification

189 Learners

(78)
Get certified from
Blogs on Latest Technologiets

Our Student Reviews

639+ Positive Reviews on Google
500+ Positive Reviews on Facebook
350+ Positive Reviews on Justdial