Top Python Interview Questions and Answers

By | October 19, 2021
Python Interview Questions

Python is one of the most versatile and powerful programming languages. It has a very bright future and promises many opportunities for its developers. So, whenever you apply for a job as a Python developer, you have to face the Python interview questions where the interviewer will test your python skills. It has often been seen that during the interview, the interviewer asks questions from core Python and many candidates are not able to answer those.

So, it is highly recommended to make your basics concepts clear. Here in this article, we have provided the Top 100+ Python interview questions that are frequently asked during Python interviews. We hope these Python interview questions and answers would help you to crack the interview.

Vamware

Top Python Interview Questions and Answers

The Python Interview Questions and Answers are classified into the following categories:

  • Python Basic Interview Questions
  • Intermediate interview questions
  • Python Coding Interview Questions

Python Basic Interview Questions

In most Python interviews, the interviewer will first check your basic knowledge of the programming language, i.e. core Python programming. In the basic Python interview questions, you face problems from Python core syntax and Python data structures. On the basis of your answer, the interviewer will estimate your python skills and may further ask you intermediate and advanced Python interview questions. Let’s look at some of the most important basic Python interview questions:

1. What is Python?

Answer: Python is a popular, high-level, object-oriented, interpreted programming language. Its easy-to-read and understandable syntax make it one of the easiest programming languages. This also reduces its program maintenance cost.

2. What do you mean by an interpreted programming language?

Answer: An interpreted programming language is a type of programming language that uses an interpreter to execute the program code. In an interpreted programming language, the code gets directly executed without compiling into machine code.

3. What is the latest version of Python?

Answer: The latest ongoing series of Python is Python 3.10.0, that first released on 4 October 2021.

4. Name some main features of Python for which it is popular.

Answer:

  1. It supports the functional and structured programming paradigms and also follows the concepts of OOPs.
  2. Python is a dynamic language.
  3. It has automatic garbage collection.
  4. It is very easy to interpret.

5. Tell some benefits of Python.

Answer:

  • It is a dynamic language.
  • It follows the object-oriented programming paradigm.
  • Apart from desktop applications, Python is also used for web development.
  • 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.
  • A python is a superior option for data science.

6. How Python is a dynamically typed language?

Answer: In Python, we do not need to define the type of variable we declare. The type of variable is unknown until the interpreter executes the code. So, the declaration of the variable type is of no use. Python binds the value with the variable name and stores the value at the memory location. And using the variable name, we can access the value of the variable and we can also change the value and data type of the variable throughout the program. For example:

var1=10 # var1 is an integer type

var2 ="Hello world" # var2 is a string

7. What is the purpose of the pass keyword do and how do you use it?

Answer: The pass is a special keyword in Python that performs the NULL operation. In Python, if you declare an if statement or a function, you have to define its body or statement. If you do not define it, the python interpreter will throw an error. To overcome this error, you can use the pass keyword inside the if and functions statements. For example:

remove_h= "hello world"

for i in remove_h:
    if i==h:
        pass
    else:
        print(i)

Output
l
l
o
w
o
r
l
d

8. Name all the inbuilt data types in Python.

Answer: Python has 6 inbuilt data types:

  1. Numbers in Python represent the numeric values.
  2. Strings in Python represent the sequence of characters inside the double and single quotes.
  3. Python list is an ordered and mutable data structure that can store multiple data values.
  4. Tuples in Python are ordered and immutable data structures that can store multiple data values.
  5. Python dictionaries are unordered and mutable data structures that store elements in the form of key/value pairs.
  6. Sets in Python are unordered and mutable data structures that only contain unique element values.

9. What are mutable and immutable data types?

Answer: Mutable data types in Python are those whose values can be changed. This includes lists, dictionaries, and sets. On the other hand, immutable are those data types which once have been assigned cannot be changed. Strings, tuples and numbers are immutable data types.

10. What are sets in Python?

Answer: Sets are unordered collections of data values that are immutable and do not accept repetitive values. Sets are iterable objects but do not support indexing. For example:

#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

11. What are tuples in Python?

Answer: A tuple is an ordered and immutable inbuilt Python data structure. It can store heterogeneous elements but it is generally used to store homogeneous data elements. Like lists, tuples also support indexing and slicing to retrieve elements. For instance:

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

Output

3

12. What are dictionaries in Python?

Answer: Python dictionaries are the collections of keys and value pairs separated by a colon. A dictionary key can only be represented by an immutable data type whereas a value could be of any data type. For instance:

>>> dict = {"one": "its one", "two" :  "its two", "three" : "its three"}
>>> print( dict["two"]) 
>>> its two # output

13. Can we use a list as a key of a dictionary?

Answer: No, the keys of the dictionary are supposed to be immutable, but the list is a mutable data type. However, we can use a string and tuple as a dictionary key.

14. Write a code to convert 144 into a string value.

Answer: To convert any data object or value to a string, we can use the str() method in Python.

str(144)

15. What are *args?

Answer: *args can accept a number of arguments passed to a function and treat those as a tuple. For instance:

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’>

16. What are **kwargs in Python?

Answer: **kwargs are similar to *args in that it is a special syntax that can accept a number of arguments passed to a function. However, in kwargs, the passed arguments are treated as dictionaries. For example:

def kwa(**kwargs):
    print(kwargs)
    print(type(kwargs))

kwa(x="hello", y="world",z=4)

Output

{'x': 'hello', 'y': 'world', 'z': 4}

<class 'dict'>

17. What does the end statement do in Python?

Answer: Whenever we use the print() method to print a statement in Python, the statement gets printed in a new line. The end is an additional parameter of the print() method, which have a value of ‘\n’ by default. That’s why every print() statement prints in a new line.

We can manipulate the value of the end to change the print statement format. The end parameter defines what would be the end of the print statement. For example:

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

Output

hello world
go for-it

18. What is a lambda function in Python?

Answer: Lambda function in Python is also known as an anonymous function. A lambda function represents a function without a name and it is widely used to write function statements in a single line. To create a lambda function in Python we use the lambda keyword, and as a normal user-defined function it can accept arguments and return a value. For instance:

#A 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)

19. What is the difference between Python list and Python tuple?

Answer:

Python list Python Tuples
A Python list is a mutable data structure. Python tuples are immutable data structures.
A list consumes more memory space as compared to a tuple. Tuples consume less space as compared to the Python list.
The iterating process takes more time in the Python list. Iterating processes take less time in Python tuple as compared to the python list.
An operation like insertion and deletion is much faster in a Python list. Accessing individual elements is faster in a Python tuple.
Lists support more methods as compared to tuples. Tuples do not have many in-built methods.
A Python list is widely used when we want to store heterogeneous data values. A tuple is generally used for homogeneous data values.
To define a list, we have to use the square bracket. To define a tuple, we use the parenthesis.

Code Example:

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

20. What is negative indexing in python?

Answer: Python data types, such as lists, tuples, and strings support positive as well as negative indexing. In negative indexing, we fetch the data values from the end of the data structure. For example, if you pass -1 index it will call the last value of the list and if you call the -2 indexing, it will fetch the second-to-last value in the list.

Code Example:

list1=[0,1,2,3,4,5]

print(list1[-1])

print(list1[-2])

Outputs

5
4

21. What are the exceptions in Python?

Answer: Exceptions in Python are the errors that generally occur during the runtime. FileNotFoundError, ZeroDivisionError, ValueError and ImportError are some of the most common Python exceptions.

Code Example:

num = int(input("enter number: "))

print(num)

Output

enter number: one
Traceback (most recent call last):
num = int(input("enter number: "))
ValueError: invalid literal for int() with base 10: 'one'

22. How can we raise an exception in Python?

Answer: In Python, we have the raise keyword to raise an exception.

Code Example:

print(" hello ")

raise ValueError

print(" world ")

Output

hello

ValueError

23. How can we import modules in Python?

Answer: There are 3 methods we can use to import a module in a Python script. These are:

1. import numpy #this import the numpy module

2. import numpy as np  # this import the numpy module with alias name np

3. from numpy import *  #this will import all the method and classes present in the numpy module

24. Does Python have a concept of inbuilt array?

Answer: Python does not have inbuilt support for arrays like it supports lists, sets, tuples, and dictionaries. However, Python supports an inbuilt module array that provides an array data structure for python. The Python array module is not that much efficient and that’s why developers always prefer to use the NumPy array.

Code Example:

import array

arr = array.array('d', [1,2,3,4])

25. Name all the type conversion methods in Python.

Answer:

Type conversion method Description
int() It converts the object into an integer value.
float() Converts the object into a floating-point number.
list() This method converts the object into a list.
dict() Converts the object into a dictionary.
tuple() It converts the object into a tuple.
str() This method converts the object into a string value.
ord() Converts the character into the corresponding ASCII value.
chr() Converts the ASCII value to a character.
oct() It converts the integer to its octal equivalent.
complex(real, imag) Converts the integer value to a complex number.
hex() This method converts the integer value to its hexadecimal equivalent.

26. What is namespace in Python?

Answer: Namespace is a naming system that allows us to have the same name for different values that are present at different scopes.

Code Example:

a  =70  #global scope
def func():
    a = 30 #local scope
    print(a)
func()
print(a)

Output

30
70

27. What is the range() function in Python?

Answer: range() is a special function in Python. It is used to iterate over a number of the sequences. The range() function can accept 3 arguments; initial state, last state, and the steps taken to reach the last point.

Code Example:

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

Output

2
4
6
8

28. What are dictionaries in Python and how they are different from lists?

Answer: A dictionary is an in-built data type in Python that stores elements in the form of key and value pairs, separated by a colon(:).

Syntax of a Python dictionary:

dic= {"key1": "value1", "key2":"value2"}
Python list Python dictionary
A Python list is an ordered data structure. A Python dictionary is an unordered data structure.
In lists, we use indexing to access the individual element. In dictionaries, we use the key name to access the individual element.
To initialize a list, we use square brackets. To initialize a dictionary, we use curly brackets.
A list occupies less memory as compared to a dictionary. A dictionary occupies more memory as compared to a list.

29. What is slicing in Python?

Answer: Slicing provides a special syntax that allows the user to retrieve a specific sequence of elements from the list. With the help of indexing, we can retrieve a single element from the list and a single character from the string, but using slicing we can retrieve a sequence of elements.

Code Example

# List slicing
lis=[1, ”hello”,3, ”world”,5,6,7, ”I am”,”here”]

print(lis[2:6])

print(list[3:8:2])

Output

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

30. Does python have a compiler?

Answer: Yes, python does have a compiler. It works automatically.

31. What is an index in python?

Answer: We use the index to retrieve a specific value from a list, string, or tuple in Python. An index is an integer that starts from 0 and goes up to n-1, where n represents the total number of elements present in the data structure.

32. Explain the map() function in Python?

Answer: map() is an inbuilt Python method that takes 2 arguments, a function and the iterable object. The map() function passes all the values of the iterable through the function one by one and returns a map object. The map() function comes very usefully when we want to perform a function on every element of the list.

Code Example

def mul3(num):
    return n*3

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

res=map(mul3,num)

print(list(res))
#output
[3,6,9,12,15]

33. Explain the filter() function.

Answer: filter() is an inbuilt Python method that is used to filter iterable object elements based on a function. It accepts two parameters, a function name and an iterable object. It passes the iterable object’s elements to the function one by one and returns an iterable object containing only those elements which satisfy the function. For instance:

#filter syntax
lis=[10,23,24,25]

res=list(filter(lambda x: x%2==0,lis))

print(res)

Output

[10,24]

34. Does Python support procedural programming?

Answer: Although Python is known for object-oriented programming, it does support procedural programming.

35. What is a function in Python?

Answer: A function is a set of code that is used to perform a specific task. Functions help to enhance the reusability of code. In Python, we use the def keyword to declare a function.

36. How many types of functions does Python have?

Answer: Like other programming languages, Python has 2 types of functions:

  1. Built-in functions (Functions that are already provided by the Python package.)
  2. User-defined functions

37. What are local variables?

Answer: When a variable is assigned inside a function, it is known as a local variable and only that specific function is allowed to use that variable.

Code Example:

def func():
    local_var = 30
    print(local_var)

38. What are global variables?

Answer: All those variables that are not defined inside a function are known as global variables and any function can access them.

Code Example:

global_var =70

def func():
    local_var = 30
    print(local_var)
func()

#output 

30

39. If we declare a function and do not define it, what will happen?

Answer: If we only declare a function and do not define it then the Python interpreter will throw an error. But using the pass keyword, we can declare a function and later define it.

40. If a Python function does not have a return statement then what will it return?

Answer: If a function does not have a return statement then it returns None.

Code Example:

def func():
    a =20

print(func())

Output

None

41. What does a break statement do in Python?

Answer: A break statement terminates the loop statement and stops the iteration. For example:

#break syntax

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

Output

0
1

42. If a break statement is used inside the nested loop then which loop it will terminate?

Answer: If we use a break statement inside a nested loop then it will terminate the innermost loop.

Code Example:

for i in range(5):
    print("outer loop", i)
        for j in range(5):
            if j ==2:
                break

print("inner loop", j)

Output

outer loop 0
inner loop 0
inner loop 1
outer loop 1
inner loop 0
inner loop 1
outer loop 2
inner loop 0
inner loop 1
outer loop 3
inner loop 0
inner loop 1
outer loop 4
inner loop 0
inner loop 1

43. What does the continue keyword do in python?

Answer: The continued statement jumps back to the loop without executing the next statements. For instance:

#continue syntax

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

#output

0
1
2
3

44. Explain ord() and chr() methods in Python.

Answer:

  • The ord() method returns an ASCII code for the character.
  • The chr() method perform inverse of ord(), i.e., it returns the corresponding value for the given ASCII code.

Code Example:

>>> ord("a")
97

>>> chr(98)
'b'

45. What does isalpha() method do in python?

Answer: isalpha() is a string method that checks if the string contains only alphabets. If the string contains only alphabets then the method will return true else it will return false. For example:

print(“Hello”.isalpha())

print(“Hello 2”.isalpha())

Output

True

False

46. What does the split() method do in Python?

Answer: split() is a Python string method that splits a string into a list of words. By default, the split() function splits the string into list values by using the white space. For instance:

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', '']

47. What is the difference between title() and capitalize() methods in Python?

Answer:  The title() method is a string method that makes the first letter of every word uppercase and the rest of the letters of the same lowercase.

Code Example:

>>> title = "this iS a TiTlE"

>>> title.title()

'This Is A Title'

The capitalize() method is also a string method but it only makes the first letter of the first word uppercase, and rest of the string lowercase.

Code Example:

>>> title = "this iS a TiTlE"

>>> title.capitalize()

'This is a title'

48. What is string concatenation and why do we use it?

Answer: String concatenation is a method that concatenates two strings. It is used to combine two strings together. For example:

>>> k= "hello"
>>> l= "world"
>>> p= k+l #string concatenation:
>>> print(p)

49. Explain the dir() method in Python?

Answer: The dir() method can return all the properties and methods of an object. With the help of the dir() method, we can find out all the properties a method support.

Code Example:

>>> dir(tuple)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

50. How can we use third-party libraries in Python?

Answer: To use a third-party library in Python, we first need to install the library. And to install the library, we can either go to the python documentation or use the pip install command.

51. What is list comprehension in Python?

Answer: A list comprehension is a method of creating a new list from an iterable object (list, tuple, set, and so on). List comprehension provides an elegant and single-line technique to create a list out of the iterable object. For example:

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

52. What does help() function do in python?

Answer: The help() function shows the documentation related to the object passed in the help parenthesis. For instance:

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

53. Name the library used to generate a random number?

Answer: Random Library.

Code Example:

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

Output

3

54. What is recursion in Python?

Answer: Recursion is a concept in which a function calls itself again and again until the base condition gets satisfied. If there is no base condition then the recursion falls in an infinite call. For instance:

#Recursion Syntax in python

def fac(n):
    if n==1:
        return 1 # Base Case
    else:
        return n*fac(n-1)

print(fac(3))

Output

6

55. What is the base case of recursion and why do we need it?

Answer: A base case in recursion refers to that statement that does not allow the function to further call itself. It is necessary for each recursion because if you do not provide a base case to the recursion then it will keep calling itself until infinity.

56. How errors are different from exceptions in Python?

Answer: Errors occur in a program due to some coding issues while exceptions occur due to interruption in the program by unusual inputs.

57. Can we directly access a function that is defined inside another function?

Answer: No.

Code Example:

def func1():
    print("func1")
    def func2():
        print("func2")

func2()
#OUTPUT
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'func2' is not defined

58. What are decorators in Python?

Answer: Decorators are one of the most powerful tools of Python. These allow wrapping a function or class into another function to enhance its functionality.

Code Example:

def  new_decorator(main_func):
    def wrap_func():
        print("******************************")
        main_func()
        print("*********************************")
        print("Thank Q for Decorating me!")
    return wrap_func

@new_decorator
def need_decorator():
    print("I want to decorate")

need_decorator()

Output:

******************************
I want to decorate
*********************************
Thank Q for Decorating me!

59. What are the generators in python?

Answer: Generators are similar to the iterators, such as lists and tuples, which can be iterated with the help of the for a loop. To create a generator, we use functions and a special statement called yield. In simple words, generators are the function that yields an output instead of returning. For instance:

#Generator Syntax
def rev():
    i=4
    while i>0:
        yield i

i=i-1
for i in rev():
    print(i)

Output

4
3
2
1

60. What does the yield statement do in Python?

Answer: The yield statement is used to define a generation. In the normal function, we use the return statement, but in generators, we use the yield statement to retrieve a result from a generator.

61. How is the yield statement different from return?

Answer: When we call a function, if it has a yield statement then it will provide a sequence of results whereas a return statement will provide a specific value. A return statement terminates the function whereas the yield does not.

62. Write a code that shows equivalence to this code my_fun=my_dec(my_fun)

Answer: @my_dec

63. What is a floor division?

Answer: It is similar to the normal division but it returns the floor integer value of the quotient. For example:

print(6//9) #floor division

print(6/9) # Normal division

Output

0
0.6666666666666666

64. What is NumPy?

Answer: NumPy is one of the most popular Python libraries. It stands for numerical python and is commonly used in Python for data science. It comes with many powerful built-in methods and a NumPy array. A NumPy array is 10 times faster than the standard Python list.

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

66. What are ternary operators in Python?

Answer: Ternary operators are similar to conditional operators and provide an alternative method to write the conditional operator code in one line. For example:

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

#output
35

67. What is functional programming?

Answer: In functional programming, we can use a function or subroutine as an argument and pass it to another function. For instance:

#Functional Programming
def fun1(fun2,arg):
    return fun2(fun2(arg))

def mul(n):
    return n*2

print(fun1(mul,10))

Output

40

68. What does the del keyword do in Python?

Answer: The del keyword is used to delete the object from the memory.

Python Interview Questions (Intermediate and Experienced)

By far we have discussed only the basic Python interview questions, i.e. Python interview questions for freshers. This is because, in most of the Python interviews, the interviewer first checks the basic Python skills of the candidate. Once the interviewer feels that the candidate has a strong understanding of the Python basics then she starts asking some intermediate and advanced Python interview questions. So now, let’s look at some of the top Python interview questions for experienced developers:

69. Why this statement often used in python: if __name__==”__main__”: ?

Answer: __name__ is a special variable in Python that executes first before anything else. It uses the if statement to check whether the file is executing directly or it’s being imported. If the file is running directly then the __name__ variable will be automatically assigned “__main__” if not it is assigned as the name of the file.

The __name__==”__main__” statement will return true if the file is executed directly and if this file is imported the __name__==”__main__” statement then it will return false.

70. What is Python GIL?

Answer: GIL stands for Global Interpreter Lock, and it is a muter or lock that allows only one thread to hold the control of the Python interpreter. This means at a time, only one thread of Python is allowed to be in an execution state.

71. Can we do multithreading in Python?

Answer: Yes, Python has some multi-threading packages that allow us to perform multi-threading in Python. But multi-threading will only be useful to us when the two modules that are running parallel have nothing to do with each other.

72. What is polymorphism in Python?

Answer: Polymorphism means having multiple forms, and it is one of the properties of the object-oriented programming paradigm. According to this property, two different objects can have the same property or method name but can have different implementations. For instance, the + operator performs addition for integer objects and concatenation for string objects.

73. What is encapsulation in Python?

Answer: Encapsulation is one of the object-oriented programming properties, and it means binding the code and data together. Python class is an example of OOPs encapsulation.

74. What is data abstraction in Python?

Answer: Data abstraction is an extension of data encapsulation, and it deals with hiding the inner functionality of a program from the user. In Python, data abstraction can be achieved by using Private properties and methods.

75. 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 are not stored in a contiguous memory location.

76. Name some tools that can be used to find a bug in Python.

Answer: PyChecker is one of the popular open-source static analysis tools that can be used to find bugs in the Python source code. Pylint is another very popular Python debugger that can warn us about the bugs and errors present in the Python source code.

77. What are predicates?

Answer: A predicate is a function that returns a True value based on some condition. For example, the Python filter() method uses a predicate function to filter out the elements from an iterable object.

Syntax:

filter(predicate, iter)

Code Example:

def is_even(num):
    return num%2==0

lis=[10,23,24,25]
res=list(filter(is_even,lis))
print(res)

Output

[10,24]

78. What does the assert statement do 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. For example:

print("hello")

assert 2+2==4

print("world")

assert 2+2==5  #error

print("world")

Output

helloworld 
AssertionError

79. What is tried and except statements in Python?

Answer: The try and except statements are part of Python exception handling. These statements are similar to if and else statements but the difference is that we use to try and accept statements specifically for error handling.

The try block represents the part of code that may contain an error or throw an error during the runtime, and the except block represents the code that tells the program what to do if there is an error in the try block. The except block gets executed if there is an error in the try block. For example:

#syntax for trying and execute statements
try:
    print('hello world')
    print('2'/3)   #error
#error
except:
    print(“there is an error in the above statement”)

Output

hello world
there is an error in the above statement

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

81. Please explain Python memory management.

Answer: Python interpreter handles 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 with the help of Python automatic garbage collector.

82. What is the difference between shallow copy and deep copy in Python?

Answer: Shallow Copy: The shallow copy creates a new object for the copied object but it does not create a new object for the nested elements.

Code Example:

old = [[1,2,3], [4,5,6], 7]

new = old.copy()   #shallow copy

#the outer layer is copied new
print("Old is New: ",old is new)

#but nested elements are same reference
print("Old 1st element is New 1st element:" ,old[0] is new[0] )

Output

Old is New:  False
Old 1st element is New 1st element: True

Deep Copy: The deep copy creates a new copy object for the outer as well as the nested elements.

Code Example:

import copy

old = [[1,2,3], [4,5,6], 7]

new = copy.deepcopy(old)

#the outer layer is created as new object
print("Old is New: ",old is new)

#nested elements are created as new objects
print("Old 1st element is New 1st element:" ,old[0] is new[0] )

Output

Old is New:  False
Old 1st element is New 1st element: False

83. How does the Python interpreter work?

Answer: The Python interpreter consists of two things, one is the compiler and the second is a virtual machine. First, the compiler takes your source code and converts it into byte code. Bytecode is simply a lower-level code that is platform-independent. Then the byte code is fed into the PVM (Python Virtual Machine). The PVM executes the byte code and gives the output.

84. Write all errors that occur in Python.

Answer:

  • Import error: It occurs when the import statement fails.
  • IndexError: It occurs when the indexing of any list fails.
  • NameError: It is generated for undefined or unknown variables.
  • SyntaxError: Comes up when the code is not written properly.
  • TypeError: It occurs when an unappropriated variable is a call.
  • ValueError: There are many other exceptions or errors in Python. There are several exceptions in the third-party libraries.

85. Explain the .py and .pyc file extensions.

Answer: The .py is the file extension of the Python program, and .pyc is the file extension of the compiled byte code file that is generated by Python.

86. What are modules and packages in Python?

Answer: A module is the Python program file that can be imported to other python programs by using the import keyword. Packages, on the other hand, are folders that contain a bunch of Python modules and subfolders. Subfolders also contain modules.

87. What is a class in Python?

Answer: A class is a blueprint of an object or instance that consists of a set of methods and properties. A class has no existence until its object or instance gets created. To create a class in Python, we use the class keyword followed by the arbitrary class name, and by convention, the class name starts with a capital letter.

Syntax of a class

class Animal:
    def method(self)
        pass

88. What are the methods in Python programming?

Answer: In general, methods are the functions that are defined inside a class. Python is an object-oriented programming language and for every data structure, there is a defined class in Python. That’s why we have many built-in methods for different data structures. But by using the class keyword in Python, we can define our own methods and properties. For example:

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

89. What is the __init__ method?

Answer: The __init__() method is a reserved method of a class and it is also known as the constructor of a class. Whenever you initialize an instance of a class, the __init__() method of the class gets called automatically. For instance:

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

90. What is the object of a class?

Answer: An object is an instance of a class and a tool to access the properties and methods of the class.

Code Example:

class Human:
    def __init__(self, name):
    self.name = name

sam = Human("sam") # sam is an object of class Human

joey = Human("joey") # joey is another object of Human class

91. What does the self keyword do in Python classes?

Answer: self is a conventional variable name that is used as the first argument of every class method and it is used to hold the instance of the object. self represents the object of the class.

92. What do you understand by inheritance of class in python?

Answer: Inheritance is a way that helps to share the functionality of one class with another class. To perform inheritance in Python, we pass the base class name in the parentheses of the drive class.

Code Example:

class Human:
    def __init__(self):
        self.species  ="Homo sapiens"

class Man(Human):
    def __init__(self, name):
        self.name = name
        super().__init__()

ram = Man("ram")
print(ram.species)

Output

Homo sapiens

93. What are Dunders in python?

Answer: Dunders stands for double underscores, and these are the special magic methods used in python that has 2 underscores, one at the beginning and the other at the end of their name. Dunders are generally used for operator overloading in Python. Some examples of dunders methods are __init__, __str__, and __del__.

94. What error will be shown if you index a key that is not a part of the dictionary?

Answer: KeyError.

95. Explain open() and close() functions in Python.

Answer: The open() function is used to open a text file for reading, writing, and appending purposes. It accepts two parameters, the filename that needs to be opened and the mode of opening the file. For example:

file_object = open("filename", mode)

The mode could be r (read), w (write), a(append), or r+(read and write).

The close() method is used to close the file object that is opened using the open() method. It is very important to close the file once you are done working with it. The close() method closes the file and terminates all the resources used by the file. For instance:

file_object.close()

96. How Python can be used for web development?

Answer: Python is well known for its web frameworks. A web framework is a tool that is used to create dynamic web applications and Python has many powerful web frameworks. Django and Flask are the two most popular Python frameworks, and Django is the second most starred web framework on GitHub.

97. What is Django?

Answer: Django is one of the most popular Python web frameworks. It can be used to create powerful and robust web applications using Python. It supports Model-View-Template architecture and uses Object Relational Mapping to perform relational database queries.

98. What is Flask?

Answer: Flask is a Python micro web framework and it uses jinja2 for web templates. Compared to Django, Flask has fewer library dependencies, which makes it a lightweight option.

99. State the difference between Flask, Pyramid, and Django.

Answer: Flask is a microframework, and it is generally used for developing small web applications. And it requires additional libraries to work with. Pyramid is larger than Flask, that’s why it is used for building big web applications. It allows developers to work with different databases, templates, and URL structures.

Django is a full-stack web framework, and it is generally used for big projects. It comes with many built-in features such as authentication and an Admin panel. Django can also work with multiple relational databases.

Also Check: Django interview questions

100. Write a python program to save an image locally from the internet whose URL is known.

Answer:

url ="http://www.somemediaurl.com/photo.jpg"
import urllib.request
urllib.request.urlretrieve(url, "local-image.jpg")

101. What are virtualenvs in Python?

Answer: The virtualenv stands for the virtual environment, and it is a python package that is used to create an isolated environment for the development, debugging and execution of a Python program. It can be installed using the following pip command:

pip install virtualenv

Python command to create a virtual environment:

python -m venv environment_name

102. What does the global keyword do in Python?

Answer: The Python global keyword allows us to use the global scope variable inside a local scope or function. Although we can access the global variable inside any user-defined local scope or function but we cannot rewrite the actual global variable but with the help of the global keyword, we can do that.

Code Example:

g_var = 100

def change_global():
    global g_var   #accessing the global variable
    g_var +=200


change_global()

print("Now the value of  g_var is:", g_var)

Output

Now the value of  g_var is: 300

103. What does the nonlocal keyword do in Python?

Answer: The Python nonlocal keyword working is similar to the global keyword. The difference is that the nonlocal keyword is used in the nested function to grab the local variable of the outer function.

Code Example:

def outer_function():
    count =200

    def nested_function():
        nonlocal count  # it will grab the count variable of its outer scope
        count +=100
        return count

    nested_function()
    print("The value of count is: ", count)
outer_function()

output

The value of count is:  300

104. What are context managers in Python?

Answer: In Python, the context manager is defined using the with keyword. The with keyword provides an elegant and clean way for writing files and exception handling code.

For example, in general, in file handling code, we have to first write the open() statement to open the file. Then write some code to read and write between the file, and at last, we have to mention the close() method to close the file. This complete process is an exception prone and many times developers find it hard to code with this syntax. But in Python, we get context managers that provide an alternative way to write file handling code that is far more efficient.

Code Example:

with open("file.txt") as file:
    data = file.read()

105. What is CPython?

Answer: CPython is the default implementation of the Python programming language. The Python we install from the official Python website is CPython. This is known as CPython because it is written in the C programming language.

>>>import platform
>>> platform.python_implementation()
'CPython'

106. What is monkey patching in Python?

Answer: Monkey patching in Python is also known as dynamic or runtime modification. With monkey patching in Python, we can modify a class and its module during runtime.

Code Example:

class monkey:
    def func_method(self):
        print("func() method of monkey class")

def func(self):
    print("function method ")


#replace the monkey method with a new function func
monkey.func_method = func

obj = monkey()
obj.func_method()

Output

function method

Python Coding Interview Questions

Often during the Python interviews, the company also organizes a Python coding test in which they ask coding-related questions to check the coding skill of the candidate. In the Python coding interview, the format of the Python interview questions could be anything. For example, you might have to debug a Python code snippet or write a python program to solve a problem or implement some data structures using Python. Here are some of the most frequent Python coding interview questions:

107. What will be the output of the following code?

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

Answer: 40

108. What would be the output of this code?

print("5"*4)

Answer: 5555

109. What would be the output of the following code?

a,b,*c=[1,2,3,4,5] 
print(a) 
print(b) 
print(c)

Answer:

1 
2 
[3, 4, 5]

110. What would be the output?

lis=[1,2,3,4,5,6,7] 
for i in range(4):
    lis.pop(i)
print(lis)

Answer: [2, 4, 6]

111. What would be the output of the following code?

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

Answer: [[4], [4], [4]]

112. 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:

True
False

113. What would be the output of the following code?

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

Answer: None

114. What would be the output of the following code?

print(bool(3<4)*20)

Answer:20

115. 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:False

116. Write code to add a delay of 1 minute.

Answer:

import time
def func():
    time.sleep(60)
    print("Print after 60 seconds")

func()

117. 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: False

118. What would be the output of the following code?

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

Answer: [1, 2, 3]

119. What would be the output of the following code?

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

Answer: 3

120. What would be the output of the following code?

def re():

    return "Hello"

    print("Hello2")

print(re())

Answer: Hello

121. What would be the output of the following code?

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

Answer: Yes

122. What would be the output?

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

Answer:[1, 2, 3, 1, 2, 3, 1, 2, 3]

123. Name the type of error for this syntax:

k=14
l = "hello world"
print(k+l)

Answer: TypeError. You cannot concatenate an integer and string directly. To do so, you have to change the type of integer to string first.

124. Write a Python code to randomize the items of a list.

Answer:

from random import shuffle
my_list = ["pen", "book", "pencil", "ink", "notebook", "eraser"]
shuffle(my_list)
my_list

Answer: ['eraser', 'pen', 'ink', 'book', 'pencil', 'notebook']

125. Write a Python program to delete a file present in the same directory as that of the Python script.

Answer: Using the python os module and the .remove method we can delete the file from our system:

import os
os.remove("filename.extension")

126. Implement bubble sort in Python.

Answer:

arr =[]
num= int(input("How many elements you want to enter in the array: "))
print("Enter the elements in the array")

for i in range(num):
    elements = int(input())
    arr.append(elements)

for k in range(len(arr)):
    for i in range(0, num-k-1):
        if arr[i] > arr[i+1]:
            arr[i],arr[i+1]=arr[i+1],arr[i]

for i in range(len(arr)):
    print(arr[i],end=' ')

127. Write a Python program to create a Fibonacci series.

Answer:

n = int(input("How many numbers you want to pick from the Fibonacci series: "))
first, second = 0, 1

print("Fibonacci sequence:")
for i in range(n):
    print(first)
    now = first + second
    first = second
    second = now

Output

How many numbers you want to pick from the Fibonacci series: 7
Fibonacci sequence:
0
1
1
2
3
5
8

128. Write a Python program to check if a number is Prime.

Answer:

num = int(input("Enter a Number: "))
if num > 1:
    for i in range(2,(num//2)+1):
        if num%i==0:
            print(num, "is a not prime number")
            break     #this if statement checks if the for loop is completely executed
     if i==num//2:
        print(num, "is a prime number")
else:
    print(num,"is not a prime number" )

Output

Enter a Number:1313 
1313 is a prime number

129. Write a python program to check if a sequence is a palindrome or not.

Answer:

Code:

string = input("Enter the String: ").lower()
temp = string[::-1]
if string == temp:    
    print(string ," is a palindrome string ")
else:
    print(string, " is not a palindrome")

Output:

Enter the String:daddad
daddad is a palindrome string

Conclusion

There are many job roles for a python developer. A Python developer could be a web developer, data analyst, data scientist, machine learning expert, artificial intelligence (AI) engineer, and so on. All the Python interview questions we have provided here cover most of the core Python concepts with some advanced Python libraries.

If you are going for a specific job role and Python is just a tool you are using, then we suggest you read the basic Python interview questions. For instance, if you have a Django interview, we recommend you first read the Python interview questions and then read Django interview questions. This will help you to refresh your Python and Django skills.

If you like this article or have any suggestions regarding Python interview questions, please let us know in the comments section below. Thanks already!

People are also reading:

Leave a Reply

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