# Top 69 Python Interview Questions and Answers

Here, you will come across some of the most frequently asked questions in Python job interviews which will help you in your interview preparation.

Let's have a look at some of the most popular and significant Python questions and answers:

Interview Questions

Ans.:

# Python | Create an empty class

In python, it required adding a pass statement to define an empty class. The pass is a special statement in python that does nothing. It just works as a dummy statement.

Ans.:

# Python | Print prime no between 1 to 100

This is an example of how to print all prime numbers between 1 and 100 using for loop.

A prime number is a natural number greater than 1 which has no other factors except 1 and the number itself.
The first few prime numbers are {2, 3, 5, 7, ….}

``````n = 100
total = 0
for i in range(2, n):
flag = True
for j in range(2,i):
if i%j == 0:
flag = False
break

if(flag == True):
total +=1
print(i)

print(f'total no of prime between 1 to {n} is {total}')``````

Ans.:

# Python | Print  Triangle pyramid pattern

This is an example of how to print the Triangle pyramid pattern. It takes an input number from the user to print the number of rows for the pattern.

``````n = int(input('enter no:'))

for i in range(n):
print(" "*(n-i-1) + '*'*(2*i+1))``````

Ans.:

# Python | Ternary Operator

python uses an if-else conditional statement in a single line to represent the Ternary Operator.

`[true] if [expression] else [false]`

Ans.:

# Python | Check whether the given value is palindrome or not

This is an example of how to check whether the given value is palindrome or not. It takes input from the user to check palindrome.

A string is said to be palindrome if the string and reverse of the string will be the same.

``````value1 = input('Enter value to check palindrome: ')

# reverse of value1
value2 = value1[::-1]

# check value and its reverses(value2) is same
if value1==value2:
print(f'{value1} is palindrome')
else:
print(f'{value1} is not palindrome')``````

Ans.:

# Python | Bubble sort program

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are not in the right order.

This is an example for bubble sort in python

``````# unordered list
l = [5,6,8,5,4,1,9,3,7]

# bubble sort approch for sorting
for i in range(len(l)-1,0,-1):
for j in range(i):
if l[j] > l[j+1]:
l[j],l[j+1] = l[j+1],l[j]

print(l)``````

Ans.:

# Python | Check whether the given number is a prime number or not

This is an example of how to check whether the given number is a prime number or not. It takes an input number from the user to check the prime number

``````n = int(input('enter no.:'))
flag = True

if n > 2:
for i in range(2, n):
if n%i == 0:
flag = False

if flag == True:
print(f'{n} is a prime number')
else:
print(f'{n} is not a prime number')
else:
print('number must be > 2')``````

Ans.:

# Python | Program to find factorial of a number

This is an example of how to find the factorial of a number in python.

The factorial of a number is a product of all the positive integers less than or equal to that number.
For example, the factorial of 5 is  5x4x3x2x1 = 120

Factorial is not defined for negative integers, and the factorial of zero is one, 0! = 1.

Check here for factorial recursive way

``````n = int(input('Enter no.:'))
fact = 1
for i in range(1,n+1):
fact *= i
print(fact)``````

Ans.:

# Python | Fibonacci series

This is an example of how to print the Fibonacci series. It takes an input number from the user to print the Fibonacci series.

The Fibonacci series is a sequence of numbers where each number in the sequence is the addition to the previous two consecutive numbers.

`0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ……..`

The first two terms are 0 and 1. The rest of the terms are obtained by adding the previous two consecutive numbers. This means the nth term is the sum of (n-1)th and (n-2)th term.

``````n = int(input('enter no:'))
a,b = 0,1
if n>1:
print(a,b,end=' ')
for i in range(2,n):
a,b = b,a+b
print(b, end=' ')``````

Ans.:

# Python | Monkey Patching

In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.

``````# m.py
class A:
def fun(self):
print("Hi")

import m
def monkey(self):
print "Hi, monkey"

m.A.func = monkey
a = m.A()
a.func()    #Hi, monkey
``````

Ans.:

# Python | __init__  constructor method

__init__ is a constructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them.

Ans.:

# Python | lists, and tuples

Lists and Tuples both are sequence data types that can store a collection of objects in Python. They are both heterogeneous data types means that you can store any kind of data type

The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that lists can be modified, appended, or sliced on the go but tuples remain constant and cannot be modified in any manner.

Ans.:

# Python | Pass Statement

The pass statement is used as a placeholder for future code. It 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.

``````def myfunction():
pass``````

Ans.:

# Python | Global, Local and Nonlocal variables

• Global variables are public variables that are defined in the global scope.
•  A variable declared inside the function's body or in the local scope is known as a local variable.
• Nonlocal Variables are used in nested functions whose local scope is not defined.

#### Q.15. Explain context manager. Can you write your own context manager example?

Ans.:

Python | context manager

Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with() statement.

``````with open('some_file', 'w') as opened_file:
opened_file.write('Hola!')``````

Ans.:

# Python | zip() Function

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator, and aggregates the elements based on the iterable passed. It returns an iterator of tuples. e.g: zip(iterator1, iterator2, iterator3 ...)

Ans.:

# Python | *args and **kwargs

• *args is a special syntax used in the function definition to pass variable-length arguments. e.g: myFun(*argv)
``````def func(*args):
for i in args:
print(i)

func(2,3,4)

#Output
2
3
4``````

• **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments. e.g: myFun(**kwargs)
``````def func(**kwargs):
for i in kwargs:
print(i, kwargs[i])

func(a=1,b=2,c=3)

#Output:
a 1
b 2
c 7``````

The words args and kwargs are a convention, and we can use anything in their place.

Ans.:

# Python | Exception Handling

Python has many built-in exceptions that are raised when your program encounters an error.

## Try and Except Statement – Catching Exceptions:

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

``````a = [1, 2, 3]
try:
print ("Second element = %d" %(a))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a))
except:
print ("An error occurred")``````

Ans.:

# Python | PYTHONPATH

PYTHONPATH is an environment variable that you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

#### Q.20. Whenever you exit Python, is all memory de-allocated?

Ans.:

The answer here is no. The modules with circular references to other objects, or to objects referenced from global namespaces, aren’t always freed on exiting Python.

Plus, it is impossible to de-allocate portions of memory reserved by the C library.

Ans.:

# Interpreted language

An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby is a prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

Ans.:

# Python | append() and extend() Function

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 that is called this append() method
• extend(another-list): Adds the elements of another list at the end of the list that is called this extend() method

Ans.:

# Python | new_style and old_style

Old-style: With old-style classes, class and type are not quite the same things.  If obj is an instance of an old-style class, obj __class__ designates the class, but the type(obj) is always an instance.

``````>>> class Foo:
...     pass
>>> x = Foo()
>>> x.__class__
<class __main__.Foo at 0x000000000535CC48>
>>> type(x)
<type 'instance'>``````

New-Style: New-style classes unify the concepts of class and type. If obj is an instance of a new-style class, type(obj) is the same as obj. __class__:

``````>>> class Foo:
...     pass

>>> obj = Foo()
>>> obj.__class__
<class '__main__.Foo'>
>>> type(obj)
<class '__main__.Foo'>
>>> obj.__class__ is type(obj)
True``````

Ans.:

# Python |  issubclass()

This is done by using a method called issubclass() provided by python. The method tells us if any class is a child of another class by returning true or false accordingly.

#### Q.25. What is a map function in Python?

Ans.:

Python | map() Function

The map() function executes a specified function for each item in an iterable. The map() function in Python has two parameters, function and iterable. The map() function 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 returns an object list of results.

#### Q.26. How do you debug code in python?

Ans.:

Using PDB we debug code in python. Some pdb commands include-

• <c> — Resume execution
• <s> — Debug step by step
• <n> — Move to next line
• <l> — List source code
• <p> — Print an expression

latest python 3.7   we can use breakpoint() to debug code

#### Q.28. “in Python, Functions Are First-class Objects.” What Do You Infer from this?

Ans.:

It means that a function can be treated just like an object. You can assign them to variables, or pass them as arguments to other functions. You can even return them from other functions.

#### Q.29. What is PEP 8?

Ans.:

PEP stands for Python Enhancement Proposal. A PEP is an official design document that describes new features proposed for Python and documents aspects of Python, like design and style, for the community. PEP 8 exists to improve the readability of Python code.

Ans.:

# Python | var() and dir()

The vars() function returns the __dict__ attribute of an object. and  The dir() function returns all properties and methods of the specified object, without the values.

Ans.:

# Python | Main Function

In the world of programming languages, the main is considered as an entry point of execution for a program. But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of main. This can be done by defining the user-defined main() function and by using the __name__  property of the python file. This __name__ variable is a special built-in variable that points to the name of the current module. This can be done as shown below:

``````def main():
print("This is main function!")

if __name__=="__main__":
main()``````

Ans.:

# Python | swapcase() Function

It is a string's function that converts all uppercase characters into lowercase and vice versa. It automatically ignores all the non-alphabetic characters.

``````string = "IT IS IN LOWERCASE."

print(string.swapcase())  ``````

Ans.:

# Python | Send an email

To send an email, Python provides smtplib and email modules. Import these modules into the created mail script and send mail by authenticating a user. It has a method SMTP(smtp-server, port). It requires two parameters to establish SMTP connection.

``````import smtplib

# Calling SMTP
s = smtplib.SMTP('smtp.gmail.com', 587)

# TLS for network security
s.starttls()

# User email Authentication

# Message to be sent
message = "Message_sender_need_to_send"

# Sending the mail

#### Q.34. What are the tools present to perform statics analysis?

Ans.:

The two static analysis tools used to find bugs in Python are Pychecker and Pylint. Pychecker detects bugs from the source code and warns about its style and complexity. While Pylint checks whether the module matches up to a coding standard.

#### Q.35. List primitive and non primitive data types?

Ans.:
• Primitive data types are Integers, Float, Strings, and Boolean.
• Non-primitive data types are Array, List, Tuples, Dictionary, Sets, and Files.

Ans.:

# Python | filter(), map(), and reduce() Functions

• filter()  function accepts two arguments, a function and an iterable, where each element of the iterable is filtered through the function to test if the item is accepted or not.
``````>>> set(filter(lambda x:x>4, range(7)))

# {5, 6}

``````

• map() function calls the specified function for each item of an iterable and returns a list of result

``````>>> set(map(lambda x:x**3, range(7)))

# {0, 1, 64, 8, 216, 27, 125}``````

• reduce() function reduces a sequence pair-wise, repeatedly until we arrive at a single value..

``````>>> reduce(lambda x,y:y-x, [1,2,3,4,5])

# 3
``````

Let’s understand this:

2-1=1
3-1=2
4-2=2
5-2=3

Hence, 3.

#### Q.37. Does Python support interfaces like Java does?

Ans.:

No. However, Abstract Base Classes (ABCs) are a feature from the abc module that let us declare what methods subclasses should implement. Python supports this module since version 2.7.

#### Q.38. What is a dynamically typed language?

Ans.:

Python is an interpreted language, that executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

Ans.:

# Python | Global, Protected, and Private

Global, Protected, and Private access modifiers in Python. Python does not use these keywords to control access modifications instead single and double underscore  ‘_’ symbols are used to specify Protected and  Private to determine the access control. The variables that are defined in the global scope are Global

Ans.:

# Python | Self

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

Ans.:

# Python | Break, Continue, and Pass

• Break: The break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
• Continue: The continue statement skips the current iteration of the statement, and the control flows to the next iteration of the loop.
• Pass: The pass keyword in Python is generally used to fill up empty blocks.

Ans.:

# Python | Generate random numbers

Python provides a module called random using which we can generate random numbers. e.g: print(random.random())

Ans.:

# Python | Generator

Functions that return an iterable set of items are called generators. It is a normal function except that it yields expression in the function. It does not implements __itr__ and next() method and reduces other overheads as well.

#### Q.44. How is Multithreading achieved in Python?

Ans.:

Python has a multi-threading package, but commonly not considered good practice to use it as it will result in increased code execution time.

Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time. The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallelly, but in reality, they are executing one by one by just taking turns using the same CPU core.

Ans.:

# Python | Dogpile effect

In case the cache expires, what happens when a client hits a website with multiple requests is what we call the dogpile effect. To avoid this, we can use a semaphore lock. When the value expires, the first process acquires the lock and then starts to generate the new value.

#### Q.46. Explain the difference between @staticmethod and @classmethod?

Ans.:

Python | Difference between @staticmethod and @classmethod

staticmethod is a method that knows nothing about the class or the instance it was called on. It just gets the arguments that were passed, no implicit first argument. Its definition is immutable via inheritance.

``````class A:

@staticmethod
def func(arg1, arg2, ...):
...
``````

classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as the first argument. Its definition follows Subclass, not Parent class, via inheritance.

``````class A:

@classmethod
def func(cls, arg1, arg2, ...):
... ``````

Ans.:

# Python | Slicing

As the name suggests, ‘slicing’ is taking parts of sequences like lists, tuples, and strings.

Syntax for slicing is [start : stop : step]

• The start is the starting index from where to slice a list or tuple
• The stop is the ending index.
• The step is the number of steps to jump.
• The default value for start is 0, stop is the number of items, and step is 1.
``````lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(numbers[1 : : 2])

#output : [2, 4, 6, 8, 10]``````

#### Q.48. List some of the most commonly used built-in modules in Python?

Ans.:

Python modules are the files having python code which can be functions, variables, or classes. These go by .py extension. The most commonly available built-in modules are:

• os
• math
• sys
• random
• re
• datetime
• JSON

Ans.:

# Python | Deep and Shallow copies

• Shallow copy does the task of creating new objects and storing references to original elements. This does not undergo recursion to create copies of nested objects. It just copies the reference details of nested objects.
• Deep copy creates an independent and new copy of an object and even copies all the nested objects of the original element recursively.

Ans.:

# Python | Iterator | (__iter__ and __next__)

Iterators are objects that can be iterated upon. The iterator protocol for Python declares that we must make use of two functions to build an iterator- iter() and next().

#### Q.51. What is the MRO in Python?

Ans.:

MRO stands for Method Resolution Order. Talking of multiple inheritances, whenever we search for an attribute in a class, Python first searches in the current class. If found, its search is satiated. If not, it moves to the parent class. It follows an approach that is left-to-right and depth-first.

Ans.:

# Python | accessors, mutators, and @property

What we call getters and setters in languages like Java, we term accessors and mutators in Python. In Java, if we have a user-defined class with the property ‘x’, we have methods like getX() and setX().

In Python, we have @property, which is syntactic sugar for property(). This lets us get and set variables without compromising on the conventions.

Ans.:

# Python | Memory manage

Python has a private heap space to hold all objects and data structures. Being programmers, we cannot access it; it is the interpreter that manages it. But with the core API, we can access some tools. The Python memory manager controls the allocation.

Additionally, an inbuilt garbage collector recycles all unused memory so it can make it available to the heap space.

#### Q.54. Difference between module and package?. addon how do you create package in python?

Ans.:

Python | Module and Package

• Module: The module is a simple Python file that contains collections of functions and global variables and with having a .py extension file. It is an executable file and to organize all the modules we have the concept called Package in Python.
• Package: The package is a simple directory having collections of modules. This directory contains Python modules and also has a __init__.py file by which the interpreter interprets it as a Package. The package is simply a namespace. The package also contains sub-packages inside it.

To create a Python package of our own, we create a directory and create a file __init__.py in it. We leave it empty. Then, in that package, we create a module(s) with whatever code we want.

Ans.:

# Python | split() and join()

You can use split() method to split a string based on a delimiter to a list of strings. and join() method is used to join a list of strings based on a delimiter to give a single string.

#### Q.56. Is it possible to call parent class without its instance creation in Python?

Ans.:

Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method.

#### Q.57. What are negative indexes and why are they used?

Ans.:

Negative numbers mean that you count from the right instead of the left. So, `list[-1]` refers to the last element, `list[-2]` is the second-last, and so on.

#### Q.58. What is a lambda function?

Ans.:

A lambda function is a small anonymous function. This function can have any number of parameters but, can have just one statement.

Ans.:

# Python | enumerate() Function

The enumerate() function is used to iterate through the sequence and retrieve the index position and its corresponding value at the same time.

``````lst = ["A","B","C"]

print (list(enumerate(lst)))

#[(0, 'A'), (1, 'B'), (2, 'C')]``````

Ans.:

# Python |  / and // Operator

• /: is a division operator and returns the Quotient value. e.g: 10/3  will return 3.33
• // : is known as floor division operator and used to return only the value of quotient before a decimal. e.g: 10//3 will return 3

Ans.:

# Python | Docstring

• A documentation string or docstring is a multiline string used to document a specific code segment.
• The docstring should describe what the function or method does.

Ans.:

# Python | Delete a file

Using command  os.remove(file_name)

Ans.:

# Python | Access Specifiers

Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not derive this from any variables. It has the concept of imitating the behavior of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public.

Ans.:

# Python | New and Override Modifiers

The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class.

Ans.:

# Python | Pickling, and Unpickling

The pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

Ans.:

# Python | strip() Function | Remove whitespaces from a string

To remove the whitespaces and trailing spaces from the string, Python provides a strip([str]) built-in function. This function returns a copy of the string after removing whitespaces if present. Otherwise returns the original string.

``````string = "  Python "

print(string.strip())  ``````

#### Q.67. Why is finalize used?

Ans.:

Finalize method is used for freeing up the unmanaged resources and cleaning up before the garbage collection method is invoked. This helps in performing memory management tasks.

#### Q.68. What is yield in Python?

Ans.:

yield is a keyword beares the ability to turn any function into a generator.  Much like the standard return keyword, but returns a generator object. It is also true that one function may observe multiple yields.

``````def odds(n):
odd=[i for i in range(n+1) if i%2!=0]
for i in odd:
yield i

for i in odds(8):
print(i)``````

The output of the above code is

1
3
5
7

Ans.:

# Python | namedtuple

A namedtuple will let us access a tuple’s elements using a name/label. We use the function namedtuple() for this, and import it from collections.

``````>>> from collections import namedtuple

#format
>>> result=namedtuple('result','Physics Chemistry Maths')

#declaring the tuple
>>> Chris=result(Physics=86,Chemistry=92,Maths=80)

>>> Chris.Chemistry
# 92``````