Top Python Interview Questions & Answers

Updated: May 21

Python is simple to learn, and once you do, you can apply your knowledge to a rewarding job in the fast growing data science field. Even better, as new machine learning applications emerge every day, the need for Python programmers will expand, boosting your job prospects. Intrigued? Wonderful! Continue reading to learn about Python's advantages..

So let’s get started with the Top Python Interview Questions & Answers

  1. What is python?

  2. What do you mean by python modules?

  3. What will be the output when we use / and // for division?

  4. What is PYTHONPATH?

  5. Mention the use of the split function in Python?

  6. Differentiate between local and global variables in Python.

  7. What is the functionality of filter(), map() and reduce() functions?

  8. What is a scope in python?

  9. List data types supported in python.

  10. What are negative indexes and why are they used? .. and more

 

Top Data Structures Interview Questions PDF

Mobiprep handbooks are free placement preparation tools that you can download and use to ace any firm placement process. To provide the finest placement preparation, we've compiled a list of the 40 most significant MCQ questions with full explanations.

Top 40 Data Structures Interview Questions and Answers
.pdf
Download PDF • 323KB




 

These top Python Interview questions have been segmented into three sections:

Basic Python Interview Questions

Question 1. What is python?

Python is a high-level scripting language which can be used for a wide variety of text processing, system administration and internet-related tasks.

Unlike many similar languages, it’s core language is very small and easy to master, while allowing the addition of modules to perform a virtually limitless variety tasks.

Python is a true object-oriented language, and is available on a wide variety of platforms.

 

Question 2.What do you mean by python modules?

Modules: Python module can be defined as a python program file which contains a python code including python functions, class, or variables.

In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We may have a runnable code inside the python module. A module in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the specific module.

Syntax:

import <module-name>

Every module has its own functions, those can be accessed with . (dot)

 

Question 3. What will be the output when we use / and // for division?

/ – divides the number and display the quotient in floating point

// – divides the number and display the quotient in integers

 

Question 4. What is PYTHONPATH?

It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories.

The interpreter uses it to determine which module to load.

 

Question 5. Mention the use of the split function in Python?

The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.

 

Question 6. Differentiate between local and global variables in Python.

Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

 

Question 7. What is the functionality of filter(), map() and reduce() functions?

> filter() – enables you to extract a subset of values based on conditional logic.

> map() – it is a built-in function that applies the function to each item in an iterable.

> reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed.30 Essential.

 

Question 8. What is a scope in python?

A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program.

1. A local scope refers to the local objects available in the current function.

2. A global scope refers to the objects available throught the code execution since their inception.

3. A module-level scope refers to the global objects of the current module accessible in the program.

4. 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..

 

Question 9. List data types supported in python.

Python has five standard data types:


Numbers

Strings

Lists

Tuples

Dictionaries

 

Question 10. What are negative indexes and why are they used?

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in the correct order.

 

Question 11. When does a dictionary is used instead of a list?

>Dictionaries – are best suited when the data is labeled, i.e., the data is a record with field names.

>lists – are a better option to store collections of un-labeled items say all the files and subdirectories in a folder. List comprehension is used to construct lists in a natural way.

>Generally, Search operation on dictionary object is faster than searching a list object.

 

Question 12. List some features of python programming.

>It provides very high-level dynamic data types and supports dynamic type checking.

>It supports automatic garbage collection.

>It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

>It supports functional and structured programming methods as well as OOP.

>It can be used as a scripting language or can be compiled to byte-code for building large applications

 

Question 13. Explain shallow copy in python.

When there is a creation of new instance type and it maintains the values, which are copied in the new instance, Shallow copy is utilized.

Like values, Shallow copy is also helpful in copying the reference pointers.

 

Question 14. What is the difference between .py and .pyc files?

1. .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.

2. Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.

3. Having .pyc file saves you the compilation time.

 

Question 15. What are decorators in python?

Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented by the @decorator_name in Python and are called in bottom-up fashion.

EXAMPLE:

# decorator function to convert to lowercase
def lowercase_decorator(function):
def wrapper():
func = function()
string_lowercase = func.lower()
return string_lowercase
return wrapper

# decorator function to split words
def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper

@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
return 'Hello World'

hello() # output => [ 'hello' , 'world' ]

 

Intermediate Python Interview Questions


Question 16. How memory is managed in Python?

Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.

The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code. Python also have an inbuilt garbage collector, which recycle all the unused memory andfrees the memory and makes it available to the heap space

 

Question 17. How do you create text files in python?

We can create the text files by using the syntax:

Variable name=open (“file.txt”, file mode)

For ex: f= open ("hello.txt","w+")

> We declared the variable f to open a file named hello.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or

operation we want to do on the file

> Here we used "w" letter in our argument, which indicates write and the plus sign that means it will create a file if it does not exist in library.

 

Question 18. List and describe file modes in python.

> 'r' This is the default mode. It Opens file for reading.

> 'w' This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file.

> 'x' Creates a new file. If file already exists, the operation fails.

> 'a' Open file in append mode. If file does not exist, it creates a new file.

> 't' This is the default mode. It opens in text mode.

> 'b' This opens in binary mode.

> '+' This will open a file for reading and writing (updating)

 

Question 19. What do you mean by *args **kwargs?

We can use *args when we are not sure how many args we are going to pass to a function. We can also use 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 *args and **kwargs are a convention.You can also use *hello and **world.

 

Question 20. What is the purpose of PYTHONSTARTUP, PYTHONCASEOK and PYTHONHOME environment variable?

1. PYTHONSTARTUP: It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

2. PYTHONCASEOK: It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

3. PYTHONHOME: It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

 

Question 21. How list is different from tuple in python?

> List are mutable (editable) while Tuple is immutable which can’t be edited.

> Lists are slower when compared with Tuples.

> List can have multiple data type in the single list where it can’t happen while using a tuple.

> Syntax: list = [1,’python’, 2.0] Syntax: tuple = [1, 2, 3]

 

Question 22. What is a dictionary in python?

Dictionary is one of the built-in datatype in python which is represented with key and corresponding values to it. These are indexed based on keys.

Example: Dict = {‘Name’: ‘Arjun’, ‘Age’: 21, ‘School’: ‘KVS’}

print (Dict [Name]) >O/P: Arjun

print (Dict [Age]) >O/P: 21

print (Dict [School’]) >O/P: KVS

In the above example Name, Age and School are Keys whereas the O/P are the corresponding values assigned to that keys.

 

Question 23. Explain inheritence in python programming.

As Python follows an object-oriented programming paradigm, classes in Python have the ability to inherit the properties of another class. This process is known as inheritance. Inheritance provides the code reusability feature. The class that is being inherited is called a superclass and the class that inherits the superclass is called a derived or child class.

Following types of inheritance are supported in Python:

> Single inheritance: When a class inherits only one superclass

> Multiple inheritance: When a class inherits multiple superclasses

> Multilevel inheritance: When a class inherits a superclass and then another class inherits this derived class forming a ‘parent, child, and grandchild’ class structure

> Hierarchical inheritance: When one superclass is inherited by multiple derived classes

 

Question 24. Write a python code to count the number of Capital letters in a file.

with open(A_LARGE_FILE) as countletter:
count = 0
text = countletter.read()
for character in text:
if character.isupper():
count += 1
 

Question 25. Discuss four string methods. 1. s.upper(): This function returns a copy of a string s to uppercase. As strings are immutable, the original string s will remain same.

>>> st= “hello”

>>> st1=st.upper()

>>> print(st1)

'HELLO'

>>> print( st) #no change in original string

'hello'


2. s.lower(): This method is used to convert a string s to lowercase. It returns a copy of original string after conversion, and original string is intact.

>>> st='HELLO'

>>> st1=st.lower()

>>> print(st1)

hello

>>> print(st) #no change in original string

HELLO


3. s.find(s1) : The find() function is used to search for a substring s1 in the string s. If found, the index position of first occurrence of s1 in s, is returned. If s1 is not found in s, then -1 is returned.

>>> st='hello'

>>> i=st.find('l')

>>> print(i) #output is 2

>>> i=st.find('lo')

>>> print(i) #output is 3

>>> print(st.find(‘x’)) #output is -1


4. s.strip(): Returns a copy of string s by removing leading and trailing white spaces.

>>> st=" hello world "

>>> st1 = st.strip()

>>> print(st1)

hello world

 

Advanced Python Interview Questions

Question 26. Discuss some list methods.

1. append(): This method is used to add a new element at the end of a list.

>>> ls=[1,2,3]
>>> ls.append(‘hi’)
>>> ls.append(10)
>>> print(ls)
[1, 2, 3, ‘hi’, 10]

2. extend(): This method takes a list as an argument and all the elements in this list

are added at the end of invoking list.

>>> ls1=[1,2,3]
>>> ls2=[5,6]
>>> ls2.extend(ls1)
>>> print(ls2)
[5, 6, 1, 2, 3]

3. sort(): This method is used to sort the contents of the list. By default, the function will sort the items in ascending order.

>>> ls=[3,10,5, 16,-2]
>>> ls.sort()
>>> print(ls)
[-2, 3, 5, 10, 16]

4. reverse(): This method can be used to reverse the given list.

>>> ls=[4,3,1,6]
>>> ls.reverse()
>>> print(ls)
[6, 1, 3, 4]
 

Question 27. Why indendation is necessary in python?

Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block.

It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.

 

Question 28. What is pass statement 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.

The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored.


EXAMPLE:

def myEmptyFunc():
# do nothing
pass

myEmptyFunc() # nothing happens

## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block
 

Question 29. "Strings are immutable". Comment.

The objects of string class are immutable. That is, once the strings are created (or initialized), they cannot be modified. No character in the string can be

edited/deleted/added. Instead, one can create a new string using an existing string by imposing any modification required.

Try to attempt following assignment –

>>> st= “Hello World”
>>> st[3]='t'

TypeError: 'str' object does not support item assignment

Here, we are trying to change the 4th character (index 3 means, 4th character as the first index is 0) to t. The error message clearly states that an assignment of new item (a string) is not possible on string object. So, to achieve our requirement, we can create a new string using slices of existing string as below –

>>> st= “Hello World”
>>> st1= st[:3]+ 't' + st[4:]
>>> print(st1)

Helto World #l is replaced by t in new string st1

 

Question 30. What is a function and how is it defined in python ?

A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used.


Example:

def func():
print("Hi, Welcome to ROOTWORKZ")
func(); #calling the function
 

Question 31. Python program that display lines that do not contain number in a text file.


import re
fname=input("Enter file name:")
try:
fhand=open(fname)
except:
print("File cannot be opened")
exit(0)
for line in fhand:
line=line.rstrip()

if re.search('^([^0-9]*)$',line):
print(line)
 

Question 32. Write a program to search and print all the lines starting with a specific word (taken as keyboard input) in a file.


fname=input(‘Enter a file name:)
word=input(‘Enter a word to be searched:)
fhand=open(fname)
for line in fhand:
if line.startswith(word):
print(line)
fhand.close()
 

Question 33. What is __init__() method in python?

Python provides a special method called as __init__() which is similar to constructor method in other programming languages like C++/Java. The term init indicates initialization.

As the name suggests, this method is invoked automatically when the object of a class iscreated.

Consider the example given here –


class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)

OUTPUT
XYZ
23
20000

 

Question 34. What will be the output of the following program?

a = True

b = False

c = False


if a or b and c:

print ("ROOTWORKZ")

else:

print ("rootworkz")


output:


ROOTWORKZ


AND operator has higher precedence than OR operator. So, it is evaluated first. i.e, (b and c) evaluates to false.Now OR operator is evaluated. Here, (True or False) evaluates to True.

So the if condition becomes True and ROOTWORKZ is printed as output.

 

Question 35. What will be the output.


class Hello:
def __init__(self, id):
self.id = id

mono = Hello(100)

mono.__dict__['life'] = 49

print mono.life + len(mono.__dict__)

In the above program we are creating a member variable having name ‘life’ by adding it directly to the dictionary of the object ‘mono’ of class ‘Hello’. Total numbers of items in the dictionary is 2, the variables ‘life’ and ‘id’.

Therefore the size or the length of the dictionary is 2 and the variable ‘life’ is assigned a value ’49’. So the sum of the variable ‘life’ and the size of the dictionary is 49 + 2 = 51.

 

Question 36. What will be the output of the following program?


tuple = (1, 2, 3, 4)
tuple.append( (5, 6, 7) )
print(len(my_tuple))

OUTPUT:

Error

An exception will be thrown as tuples are immutable and don’t have an append method.

 

Question 37. What will be the output of the following program?


a = 2
b = '3.77'
c = -8
str1 = '{0:.4f} {0:3d} {2} {1}'.format(a, b, c)
print(str1)

output:


2.0000 2 -8 3.77


At Index 0, integer a is formatted into a float with 4 decimal points, thus 2.0000. At Index 0, a = 2 is formatted into a integer, thus it remains to 2. Index 2 and 1 values are picked next, which are -8 and 3.77 respectively.

 

Question 38. Write a python program to check whether given two strings are anagrams or not.


def check(a,b):
if(len(a)!=len(b)):
return False
else:
if(sorted(list(a)) == sorted(list(b))):
return True
else:
return False

 

Question 39. What is PEP8?

PEP8 is an official style guide given by the community to improve the readability to the top.

PEP8 enables you to write the python code more effective. Some naming conventions and comments will be helpful to share your code with other people to understand the code better.

PEP8 is a document that provides guidelines and best practices on how to write Python code. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan.

The primary focus of PEP 8 is to improve the readability and consistency of Python code


 

These Data Structure interview questions would give you an insight into what kind of questions could be asked.
Free Practice Tests

 

#DS #algorithm

50 views1 comment

Recent Posts

See All