Python is one of the most versatile and powerful programming languages. It has a very bright future and promises many opportunities for its developer. So, whenever you go for a job as a Python Developer, you have to face the interview and the interviewer will ask many questions related to Python in order to check your level in python programming. Many times, we have seen that the interviewer asked questions related to the basic python and the candidate could not even able to give their answers and then they feel embarrassing and this results from demotivation for the candidate. Here in this article we have provided Top 100 question frequently asked in the python Interviews, that would help you to crack the Interview.

Python Interview Questions

Question: Who is the creator of Python?
Answer: Guido van Rossum

Question: What is Python?
Answer: Python Interview QuestionsPython is the most useful, high-level, object-oriented, interpreted programming language.

Question: What do you mean by interpreted programming language?
Answer: An interpreted programming language in which the code gets directly executed without compilation.

Question: Tell some benefits of Python.
Answer:

  • It is Dynamic language
  • It supports object-oriented programming languages
  • It does not have a concept of access modifiers like private, public, and protected but you can use magic functions to use the methods as public or private.
  • It has a very simple syntax which makes it easy to learn.
  • Apart from desktop application python is also used for web development.

Question: What is a Dynamic type Language?
Answer: Unlike other programming languages in python for every variable, you do not need to declare its data type. That makes Python a Dynamic language.

E.g. var1=10 # var1 is an integer type
var2 =“Hello world” # var2 is a string

Question: Name the tool in python which is used to find Bugs
Answer: PyChecker and Pylint

Question: What pass keyword do and why do use it?
Answer: The pass is a special keyword in the python which performs the NULL operation when you execute a pass keyword nothing happens.

In python, if you declare an if statement or a function you have to define the function and the statement if you do not define them the python interpreter through an error. To overcome this error, you can use the pass keyword inside the if statements and functions.

e.g.

remove_h=”hello world”
for i in remove_h:
if i==h:
pass
else:
print(i)
#output
h
e
l
l
o
w
o
r
l
d

Question: Write code to get the current file directory.
Answer: import os

print(os.__file__)
#output
Users\user_name\AppData\Local\Programs\Python\Python37-32\lib\os.py

Question: Name all the inbuild datatype in python:
Answer: Python has 6 inbuilt data types

Numbers
Strings
List
Tuples
Dictionaries
Sets

Question: What are Mutable and Immutable Datatypes
Answer: Mutable are those data types in python whose value can be changed.

E.g. list, Dictionaries and Sets

Immutable are those data types once they have been assigned you cannot manipulate their values.

E.g. Strings, Tuples and Numbers

Question: Comment on Python Memory management.
Answer: Python interpreter handles the memory management. It uses private heaps to control and maintain the memory. In python the user does not get any access related to its memory management, python memory management takes control of all the memory action by itself. Python has an automatic garbage collector

Question: Write a code to convert 144 into a string
Answer:

str(144)

Question: What is a lambda function?
Answer: Lambda function is an anonymous function which can be written in a single line.

e.g.

# Normal function in python
def mul(a,b):
return a*b
mul(10,20)
#lambda function
mul=lambda a,b : a*b
mul(10,20)

Question: Give the main difference between tuple and list.
Answer: Tuples are immutable whereas lists are mutable.

e.g.

list1=[0,1,2,3,4] #list
tuple1=(0,1,2,3,4) #tuples
list1[2]=4 #Mutable
tuple1[2]=4 # it will through an error because tuples are immutable

Question: What is negative indexing in python??

Answer: Python data-types such as list, tuples and sets support the positive as well as negative indexing. In negative indexing, if you pass -1 index it will call the last value of the list or if you call -2 indexing it will the second last value of the list.

e.g.

list1=[0,1,2,3,4,5]
print(list1[-1])
print(list1[-2])

#outputs

5
4

Question: What are the methods of a class?
Answer: Methods are the functions, which are defined inside a class.

e.g

class Animal:
def method_1(self):
pass
def method_2(self):
print(“hello world”)

Question: What is a __init__ method?
Answer: __init__ method is a reserved method of a class is also known as the constructor of a class. Whenever you initialize any instance of a class the __init__ method automatically call.

E.g

class Animal:
def __init__(self):
print(“I am an Animal”)
def method_1(self):
pass
dog=Animal() #instance of a class

#Output

I am an Animal

Question: What are Exceptions in Python?
Answer: Exceptions are the errors occurs during execution of code.

Question: What Raises an Exception?
Answer: In python, you can raise an Error by using a statement raise and all the statement after it won’t execute.

e.g.

print(“hello”)
raise ValueError
print(“world”)

#output

hello
ValueError

Question: Does Python have a concept of inbuilt Array?
Answer: Python does have a list but they are not Arrays. Python does not have support for in-built array data type but you can use the array with the help of a third-party library Numpy.

Question: What range function does in python?
Answer: range() is a special function often use in python it is used to iterate over a number of the sequence. range function can accept 3 arguments initial state, last state and the steps taken to reach the last point.

e.g.

for i in range(2,10,2)
print(i)

#output

2
4
6
8

Question: What are dictionaries in python and how they are different from a list?
Answer: A dictionary is an in-built data type in python which consist of a pair of key and values separated by a colon(:).

#dictionary syntax:

dic= {“key1”: “value1”, “key2”:”value2”}

Dictionaries are the unorder collections of key and values whereas a list is an ordered collection of values.

In the list, we use the index to call a value but in dictionaries, we use keys to call the corresponding value.

Question: What error will be shown if you index a key that is not a part of the dictionary?
Answer: KeyError

Question: What is slicing in python?
Answer: Slicing gives more control to the user over a string or a list. With the help of slicing, you can retrieve any sequence of values that you want.

e.g

# List slicing
lis=[1, ”hello”,3, ”world”,5,6,7, ”I am”,”here”]
print(lis[2:6])
print(list[3:8:2])

#outputs

[3,”world”,5,6] [“world”,6,”I am”]

Question: What is a class in python?
Answer: A class is a blueprint of an object or instance which consist of a set of methods and attributes. A class have no existence until its object or instance has made.

#syntax of a class
class Animal:
def method(self)
pass

Question: What are try and except statements?
Answer: Try and except statement are the part of exception handling. The try and except statements are similar to if and else statements but the difference is we use try and except statement for the error handling.

If you write a code for the try block and if it through an error the try block stop being executed and the interpreter directly jumps to the except block to execute its code.

#syntax for try and execute statements

try:
print(“hello world”)
print(“2”/3) #error
except:
print(“there is an error in the above statement”)

#output

hello world
there is an error in the above statement

Question: What is an index in python?
Answer: In python to retrieve a specific value from a list, sting, or tuples we use the index. An Index is the integer which starts from 0 and every index corresponding to a value.

Question: What Assert statement does in python?
Answer: The assert statement checks whether the statement is True or False. If the assert statement is True nothing happens but if it is False the statement throws an AssertError.

e.g.

print(“hello”)
assert 2+2==4
print(“world”)
assert 2+2==5
print(“world”)

#output

hello
world

AssertionError

Question: What is the object of a class?
Answer: An object is an instance of a class and a tool to access the properties and method of the class.

Question: What open() and close() functions do in python?
Answer: open() function is used to open a text file for reading, writing and appending purpose.

When you open the file for reading, writing or appending you also need to close it so close function helps to close the open file.

Question: What does a map function do in python?
Answer: A map() is an inbuilt function in python which take 2 arguments. The 1st argument is the function and an iterable as its 2nd argument. The map function passes all the values of the iterable through the function one by one and at last return a list.

#syntax for the map()

def mul3(num):
return n*3
num=[1,2,3,4,5]
res=map(mul3,num)
print(list(res))

Question: How python can be used for web development?
Answer: Python has many frameworks like Django, flask, etc. which are used for web development, and you can simply get these frameworks by using pip install command.

Question: Explain filter() function.
Answer: filter() is an inbuilt function in python that is used to filter an iterable by removing items which do not match the predicate.

#filter syntax

lis=[10,23,24,25]
res=list(filter(lambda x: x%2==0,lis))
print(res)

#output

[10,24]

Question: What are predicates?
Answer: Predicates are those functions which return a Boolean

Question: Does python support procedural programming?
Answer: Yes, though python is known for its object-oriented programming, python does support the procedural programming.

Question: In python how can we use the third-party libraries?
Answer: To use the 3rd party libraries first we need to install those. You can go to the python documentation to install the libraries or you can use the pip install command to install the libraries.

Question: What is a function?
Answer: A function is a set of code which is used to perform a task. This help to enhance the reusability of code. In python to declare a function, we use a keyword def.

Question: How many types of Function does python have?
Answer: Like other programming, language python has 2 types of function

Built-in functions (functions already provided by the python)

User-defined functions

Question: If we declare a function and do not define it what will happen?
Answer: The python interpreter will throw an error.

Question: If a function does not return anything will it throw an error?
Answer: No.

Question: What a break statement does?
Answer: A break statement terminates the loop statement and stop the iteration.

e.g.

#break syntax
for i in range(4):
if i==2:
break
print(i)

#output

0
1

Question: If a break statement uses inside the nested loop which loop it will terminate?
Answer: If we use a break statement inside a nested loop it will terminate the innermost loop.

Question: What do you understand by inheritance of class in python?
Answer: Inheritance is a way which helps to share the functionality of one class with another class. To inherit a class from another class we pass the base class name in the parentheses of derived or subclass.

Question: What are dunders in python?
Answer: Dunders are the special magic methods used in python which have 2 underscores at the beginning and end of their name. some e.g. of dunders methods are __init__, __str__, __del__,etc

What are the sets?
Answer: Sets are the unordered collections of data types which are immutable and do not accept the repetitive values. You are iterable but you cannot use index retrieve a value from a set.

#set syntax
sets={1,2,3,4,5,5,6,6,6,6}
print(sets)
#output:

{1,2,3,4,5,6} #it eliminates the repetitive values

Question: What are tuples?
Answer: Tuples are similar to a list, like the list in tuple we use indices to retrieve its values. The only difference is tuples are immutable whereas lists are mutable.

e.g.
tup=(1,2,3,4,5) # to declare a tuple we use parentheses
print(tup[2])

#output

3

Question: Can we use a list as a key of a dictionary?
Answer: No, the keys of the dictionary should be an immutable datatype such as tuples, strings or numbers.

Question: Why this statement often use in python if __name__==”__main__”: ?
Answer: __name__ is a special variable in the python which executes first before anything else. It uses with the if statement to check whether the file is executing directly or it’s being imported. If the file is running directly the __name__ variable will be automatically assigned “__main__” if not it assigned as the name of the file.

Question: What are *args?
Answer: *args is a special syntax which can accept a number of arguments pass to a function and treat those as a tuple.

e.g.

def arg(*args):
print(args)
print(type(args))
arg(1,2,3,4,5,6,7,8)

#output

(1,2,3,4,5,6,7,8)
<class ‘tuple’>

Question: What are **kwargs in python?
Answer: **kwargs are similar to *args, a special syntax which can accept a number of argument pass to function but in kwargs it treat the passed argument as a Dictionary.

e.g.

def kwa(**kwargs):
print(kwargs)
print(type(kwargs))
kwa(x=”hello”, y=”world”,z=4)

#output

{'x': 'hello', 'y': 'world', 'z': 4}
<class 'dict'>

Question: What does the end statement does in python?
Answer: Whenever we use a print() statement it always prints it on a new line. An end statement is an additional statement with the print() which have a value of ‘\n’ by default that’s why every print() statement print on a new line. We can manipulate the value of end to change the print statement format.

e.g.

print(“hello”, end=’ ‘)
print(“world”) #here end value id ‘\n’ by default
print(“go for”, end=”-“)
print(“it”)

#output

hello world
go for-it

Question: What is Django?
Answer: Django is one of the most widely used frameworks of Python.

Question: What does help() function do in python?
Answer: help() function show the documentation related to the object passed in the help parenthesis.

e.g.

lis=[1,2,3,4] help(lis)

Question: What are list comprehensions in python?
Answer: A list comprehension is a method of creating a new list from an iterable.

E.g.

#List comprehension Syntax:
old_list=[1,2,3,4,5,6]
new_list=[i*2 for i in old_list]
print(new_list)

#output

[2, 4, 6, 8, 10, 12]

Question: What does a continue keyword do in python?
Answer: The continue statement jump back to the loop without executing the next statements.

#continue syntax

for i in range(10):
if i>3:
continue
print(i)

#output

0
1
2
3

Question: What ord() and chr() functions do in python?
Answer: The ord() return an ASCII code of the argument pass in it. Whereas the chr() perform adverse of ord(), it returns the corresponding value for the given ASCII code.

e.g.

print(ord(‘a’))
print(chr(97))
</pre.
#output

97
‘a’

Question: What does isaplha() function do in python?
Answer: isalpha() is a special method used to check whether the given string containing only alphabets or not. If the string contains only alphabets the method will return true else it will return False.

e.g.
print(“Hello”.isalpha())
print(“Hello 2”.isalpha())

#output

True
False

Question: What does a split() function do?
Answer: split() is a function used with a string to get a list out of it. By default, the split function split the string into list values by using the white space.

e.g.

str=’hello world I am here’
print(str.split())
print(str.split(‘e’))

#output
[‘hello’, ‘world’, ‘I’, ‘am’, ‘here’] [‘h’, ‘llo world I am h’, ‘r’, ”]

Question: What does title() and join() function do in python?
Answer: The title() function used with the string and it uppercase the first letter of each word and lowercase the rest.

The join() function used with tuples and list and it helps to join all the values of tuple or list altogether and return a string.

e.g

jlist=['1','2','3']
print("".join(jlist))
str="helLO woRld"
print(str.title())

#Output

123

Hello World

Question: What is Python GIL?
Answer: GIL stands for Global Interpreter Lock, and it is a muter or lock which allow only one thread to hold the control of the Python interpreter.

Question: How the python list is different from a linked list.
Answer: The Python list uses the contiguous memory location to store the list values like an array, whereas the linked List values do not store in a contiguous memory location.

Question: Name the library used to generate a random number?

Answer: Random Library

e.g.

from random import randint
print(randint(1,10))

#output

3

Question: What is recursion?
Answer: Recursion is a concept in which a function call itself it is also known as self-reference.

e.g.

#Recursion Syntax in python
def fac(n):
if n==1:
return 1 # Base Case
else:
return n*fac(n-1)
print(fac(3))

#output

Question: What is the base case of recursion and why do we need it?
Answer: A base case in a recursion refers to that statement that does not allow the function to further call itself. A base case is necessary for each recursion if you do not provide a base case to the recursion it will throw infinite results.

Question: How errors are different from the exception in python?
Answer: Error rise in a program due to some coding issue while exception occurs due to an interruption in the program by unusual inputs.

Question: What does for loop works in python.
Answer: For loop use an iterator to move from one point to another, it iterates from one value to the last of the iterators.

Question: Can we directly access a function which is defined inside another function?
Answer: No.

Question: What are decorators in python?
Answer: Decorators are one of the most powerful tools of python, which allow wrapping a function or class into another function to enhance its functionality.

Question: What would be the output of this code?

lis=[1,2,3,”hello”,”world”]
print(lis[-1])

Answer: “world”

Question: What is a floor division?
Answer: It is similar to the normal division but in this, we use double division sign to divide two integers and it returns an integer.

e.g.

print(6//9) #floor division
print(6/9) # Normal division

#output

0

0.6666666666666666

Question: What are the Generators in python?
Answer: Generators are similar to the iterators such as list and tuples, which can be iterate with the help of for loop. To create a generator, we use functions and a special statement called yield. In simple words, generators are the function which yield output instead of returning.

#Generator Syntax

def rev():
def rev():
i=4
while i>0:
yield i
i=i-1
for i in rev():
print(i)

#Output

4
3
2
1

Question: What does yield statement do in python?
Answer: Yield statement used to define a generator, in the normal function we use return statement but in generators, we use yield statement to retrieve a result from a generator.

Question: How yield statement is different from return?
Answer: When we call a function if it has a yield statement then it will provide a sequence of result whereas a return statement will provide a specific value. A return statement terminates the function whereas the yield cannot.

Question: Write a code which show an equivalence to this code my_fun=my_dec(my_fun)
Answer: @my_dec

Question: What is NumPy?
Answer: Numpy is a very powerful and widely used package in python. The NumPY package id highly used for the data science and scientific research.

Question: What is a Docstring in python?
Answer: Docstring means documentation string and it is used to provide some additional information regarding the Python modules, Functions, Classes and Methods.

Question: What do we do to copy an object in python?
Answer: To copy an object, we use a copy module.

Question: What will be the output of the following code?

lis1=[1,2,3,4,5]
lis2=lis1
lis1[3]=40
print(lis2[3])

#Output

40

Question: What self-variable does in python classes?
Answer: self is a conventional variable which is used as the first argument of every class method and it is used to hold the instance of the object.

Question: What are ternary operators in python?
Answer: Ternary operators are similar to the conditional operator and provide an alternative method to write the conditional operator code.

e.g.
x= 35
y=75
min = x if x < y else y
print(min)

#output

35

Question: What is functional programming?
Answer: In functional programming we can use a function as an argument and pass it to the another function.

e.g.

#Functional Programming
def fun1(fun2,arg):
return fun2(fun2(arg))
def mul(n):
return n*2
print(fun1(mul,10))

#Output

40

Question: What does del() function do in python?
Answer: The del() function is used to delete the object.

Question: What phenomena use when you transverse through a dictionary object in python?
Answer: Tuple unpacking

#Output key is key1 and values is val1 key is key2 and values is val2 key is key3 and values is val3 Question: Can we define a class inside a class in python? Answer: Yes. OUTPUT Questions Question: What would be the output of this code print(“5”*4) Answer: #output 5555 Question: What would be the output of the following code a,b,*c=[1,2,3,4,5] print(a) print(b) print(c) Answer: #output 1 2 [3, 4, 5] Question: what would be the output? lis=[1,2,3,4,5,6,7] for i in range(4):

  lis.pop(i)
print(lis)

Answer: #Output

[2, 4, 6]

Question: what would be the output of the following code?

lis=[[]]*3
lis[0].append(4)
print(lis)

Answer:

#Output

[[4], [4], [4]]

Question: what would be the output of the following code?

Lis1=[1,2,3,4]
Lis2=[1,2,3,4]
print(Lis1==Lis2)
print(Lis1 is Lis2)

Answer:

#Output

True
False

Question: What would be the Output of the following Code?

lis=[10,3,20,19,4]
print(lis.sort())

# OUTPUT

None

Question: What would be the output of the following code?
print(bool(3<4)*20)

Answer:

#Output

20

Question: What would be the output of the following code?
print(“70’+’33”)

#Output

70’+’33

Question: What would be the output of the following code?

lis=[1,2,3,4,5,6,7]
a=lis.sort()
b=sorted(lis)
if a==b:
  print(True)
else:
  print(False)

Answer:

#Output

False

Question: Write code to add a delay of 1 min.
Answer:

Question: What would be the output of the following code?

lis1,lis2=[1,2,3],[1,2,3]
if id(lis1)==id(lis2):
  print(True)
else:
  print(False)

Answer:

#Output

False

Question: What would be the output of the following code?

lis1=[1,2,3]
lis2=lis1
del(lis1)
print(lis2)

Answer:

#Output

[1, 2, 3]

Question: What would be the output of the following code?

print(3**1**2**4)

#Output

3

Question: What would be the output of the following code?

def re():
return "Hello"
print("Hello2")
print(re())

Answer:

#Output
Hello”

Question: What would be the Output of the following code?

lis=["1100110011001100","11001100"]
if lis[1]in lis[0]:
  print("yes")
else:
  print("No")

Answer:

#Output
Yes

Question: What would be the output?

print([1,2,3]*3)
Answer:

#Output

[1, 2, 3, 1, 2, 3, 1, 2, 3]

Leave a Reply

Your email address will not be published. Required fields are marked *