Top 154+ Python Interview Questions and Answers in 2024

Posted in /  

Top 154+ Python Interview Questions and Answers in 2024

Vinay Khatri
Last updated on April 17, 2024

    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 Python interview questions where the interviewer will test your Python skills. It has often been seen that the interviewer asks questions from core Python during the interview, and many candidates cannot answer those.

    So, it is highly recommended to make your basic concepts clear.

    In this article, we have provided the frequently asked questions during Python interviews. We hope these will help you to crack the interview.

    Top Python Interview Questions and Answers

    Basic Python Interview Questions for Freshers

    In most Python interviews, the interviewer will first check your basic knowledge of the programming language, i.e., core Python programming. In the basic questions, you face problems with Python core syntax and Python data structures . Based on your answer, the interviewer will estimate your Python skills and may further ask you intermediate and advanced Python questions.

    1. What is Python?

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

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

    An interpreted programming language is a language that uses an interpreter to execute the program code. The code gets directly executed in an interpreted programming language without compiling into machine code.

    3. Is Python a scripting language or a programming language?

    According to the definition of scripting and programming language, Python comes in the league of scripting languages. Still, in general, Python is introduced as a high-level programming language. The critical difference between scripting and programming languages is that a scripting language does not require the additional compilation step, and its code gets directly interpreted.

    On the other hand, in programming languages, the code first gets compiled, converted into low-level byte code, and then executed.

    4. What is PEP 8 in Python?

    PEP stands for Python Enhancement Proposal, which is the official documentation of Python that informs the Python community about the features, syntax, and the new release of Python. PEP 8 comes under the 8th serial number of this documentation, and it defines the Style Guide for Python Code , which means the standard conventions to write legible Python code.

    Some of the essential code-writing styles defined in PEP 8 are:

    • There should be four spaces per indentation level.
    • Spaces and tabs can be used for indentation (but one at a time). It is always preferred to use tabs for consistent indentation.
    • The maximum number of characters a line should have is 79.
    • There should be two line spaces between two class or function definitions.
    • There should be 1 line space between the two method definitions.

    5. What is the latest version of Python?

    The latest ongoing series of Python is Python 3.10.0. It was first released on 4 October 2021.

    6. Name some main features of Python.

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

    7. Tell some benefits of Python.

    • 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 straightforward syntax that makes it easy to learn.
    • Python programming language is a superior option for data science.

    8. How is Python a dynamically typed language?

    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. Thus, we can access the variable's value and change the variable's value and data type throughout the program using the variable name.

    For example:

    var1=10 # var1 is an integer type
    var2 ="Hello world" # var2 is a string

    9. What is the purpose of the pass keyword? How do you use it?

    The pass is a particular keyword in Python that performs the NULL operation. In Python, if you declare an if statement or a function, you must 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.

    Example :

    remove_h= "hello world"
    for i in remove_h:
        if i==h:


    l l o w o r l d

    10. Name all the inbuilt data types in Python.

    Python has six inbuilt data types:

    1. Numbers in Python represent 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. A Python dictionary is an unordered and mutable data structure that stores elements in key/value pairs.
    6. Sets in Python are unordered and mutable data structures that only contain unique element values.

    11. What are mutable and immutable data types?

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

    12. What are sets in Python?

    Sets are unordered collections of immutable data values and do not accept repetitive values. Sets are iterable objects but do not support indexing.

    Example :

    #set syntax


    #it eliminates the repetitive values

    13. What are tuples in Python?

    A tuple is an ordered and immutable inbuilt Python data structure. It can store heterogeneous elements but 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



    14. What are dictionaries in Python?

    Python dictionaries are collections of key and value pairs separated by a colon. An immutable data type can only represent a dictionary key, 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

    15. Can we use a list as a key to a dictionary?

    No, a dictionary's keys 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.

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

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

    17. What are *args?

    *args can accept several arguments passed to a function and treat those as a tuple.

    For instance :

    def arg(*args):


    <class ‘tuple’>

    18. What are **kwargs in Python?

    **kwargs are similar to *args in that it is a special syntax that can accept several arguments passed to a function. However, in kwargs, the passed arguments are treated as dictionaries.

    For example :

    def kwa(**kwargs):
    kwa(x="hello", y="world",z=4)


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

    19. What does the end statement do in Python?

    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 print() method parameter with 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="-")


    hello world
    go for-it

    20. What is a lambda function in Python?

    A Lambda function in Python is also known as an anonymous function. A lambda function represents a function without a name and 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
    #lambda function
    mul=lambda a,b : a*b

    21. What is the difference between a Python list and a Python tuple?

    Python List Python Tuple
    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 tuples than in 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

    22. What is negative indexing in Python?

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




    23. What are the exceptions in Python?

    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.


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


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

    24. How can we raise an exception in Python?

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


    print(" hello ")
    raise ValueError
    print(" world ")



    25. How can we import modules in Python?

    We can use three methods to import a module in a Python script. These are:

    1. import numpy #this imports the numpy module
    2. import numpy as np  # this imports the numpy module with alias name np
    3. from numpy import *  #this will import all the methods and classes present in the numpy module

    26. Does Python have the concept of an inbuilt array?

    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 the Python programming language. The Python array module is not that efficient, so developers always prefer to use the NumPy array.

    Code Example:

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

    27. Name all the type conversion methods in Python.

    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.

    28. What is a namespace in Python?

    Namespace is a naming system allowing us to have the same name for different values at different scopes.


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



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

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


    for i in range(2,10,2)



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

    A dictionary is an in-built data type in Python that stores elements in 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.

    31. What is slicing in Python?

    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 we can retrieve a sequence of elements using slicing.

    Code Example

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


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

    32. Does Python have a compiler?

    Yes, Python does have a compiler . It works automatically.

    33. What is an index in Python?

    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.

    34. Explain the map() function in Python?

    map() is an inbuilt Python method that takes two arguments, a function and an iterable object. The map() function passes all the iterable values through the function individually and returns a map object. The map() function becomes useful when we want to perform a function on every list element.


    def mul3(num):
        return n*3

    35. Explain the filter() function.

    filter() is an inbuilt Python method that filters iterable object elements based on a function. It accepts two parameters, a function name, and an iterable object. It individually passes the iterable object’s elements to the function and returns an iterable object containing only those that satisfy the function.

    For instance:

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



    36. Does Python support procedural programming?

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

    37. What is a function in Python?

    A function is a set of codes 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.

    38. How many types of functions does Python have?

    Like other programming languages, Python has two types of functions:

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

    39. What are local variables?

    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.


    def func():
        local_var = 30

    40. What are global variables?

    All those variables not defined inside a function are known as global variables ; any function can access them.

    Code Example:

    global_var =70
    def func():
        local_var = 30
    #output 30

    41. What will happen if we declare a function and do not define it?

    I f we only declare a function and do not define it, the Python interpreter will throw an error. However, we can use the pass keyword to declare a function and later define it.

    42. If a Python function does not have a return statement, what will it return?

    If a function does not have a return statement, it returns None.


    def func():
        a =20



    43. What does a break statement do in Python?

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

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



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

    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:
    print("inner loop", j)


    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

    45. What does the continue keyword do in Python?

    The continue statement jumps back to the loop without executing the next statements.

    For instance:

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



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

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


    >>> ord("a")
    >>> chr(98)

    47. What does the isalpha() method do in python?

    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 2”.isalpha())



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

    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 using white space. For instance:

    str=’hello world I am here’


    ['hello', 'world', 'I', 'am', 'here']
    ['h', 'llo world I am h', 'r', '']

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

    The title() method is a string method that makes the first letter of every word uppercase and the rest of the letters 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 the rest of the string lowercase.


    >>> title = "this iS a TiTlE"
    >>> title.capitalize()
    'This is a title'

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

    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)

    51. Explain the dir() method in Python?

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


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

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

    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.

    53. What is list comprehension in Python?

    In Python, list comprehension is creating a new list from an iterable object (list, tuple, set, and so on). List comprehension provides an elegant single-line technique to create a list from the iterable object.

    For example:

    #List comprehension Syntax:
    new_list=[i*2 for i in old_list]


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

    54. What does the help() function do in python?

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


    55. Name the library used to generate a random number.

    Random Library.


    from random import randint



    56. What is recursion in Python?

    Recursion is a concept in which a function calls itself repeatedly until the base condition is satisfied. The recursion falls in an infinite call if there is no base condition. For instance

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



    57. What is the base recursion case, and why do we need it?

    A base case in recursion refers to that statement that does not allow the function to call itself further. 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.

    58. How are errors different from exceptions in Python?

    Errors occur in a program due to some coding issues, while exceptions occur due to interruptions in the program by unusual inputs.

    59. Can we directly access a function defined inside another function?



    def func1():
        def func2():


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

    60. What are decorators in Python?

    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("Thank Q for Decorating me!")
        return wrap_func
    def need_decorator():
        print("I want to decorate")


    I want to decorate
    Thank Q for Decorating me!

    61. What are the generators in Python?

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

    For instance:

    #Generator Syntax
    def rev():
        while i>0:
            yield i
    for i in rev():



    62. What does the yield statement do in Python?

    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.

    63. How is the yield statement different from the return?

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

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


    65. What is a floor division?

    It is similar to the normal division but returns the floor integer value of the quotient.

    For example:

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



    66 What is a docstring in Python?

    Docstring in Python means documentation string, which provides additional information regarding the Python modules, functions, classes, and methods.

    67. What are ternary operators in Python?

    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
    min = x if x < y else y



    68. What is functional programming?

    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



    69. What does the del keyword do in Python?

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

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


    Python OOPs Interview Questions

    Python is an object-oriented programming language, and everything in Python is treated as an object. In the Python interviews, many questions are asked about the OOPs concepts because to implement solutions to real-world problems, OOPs play an important role.

    71. What is a class in Python?

    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)

    72. What are the methods in Python programming?

    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):
        def method_2(self):
            print('hello world')

    73. How to create an empty class in Python?

    An empty class is a class that has no definitions. To define an empty class in Python, we can use the pass keyword. Even if the empty class has no body definition, we can still make its object.


    class Empty:
    #create the object for empty class
    obj= Empty() = "Something"
    print(  #something

    74. What is the __init__ method?

    The __init__() method is a reserved class method. It is the constructor equivalent in the Python programming language. 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):
    dog=Animal() #instance of a class


    I am an Animal

    75. What is the object of a class?

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


    class Human:
        def __init__(self, name): = name
    sam = Human("sam") # sam is an object of class Human
    joey = Human("joey") # joey is another object of the Human class

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

    self is a conventional variable name used as the first argument of every class method, and it is used to hold the object's instance. self represents the object of the class.

    77. What do you understand by inheritance of class in Python?

    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 derived class.


    class Human:
        def __init__(self):
            self.species  ="Homo sapiens"
    class Man(Human):
        def __init__(self, name):
   = name
    ram = Man("ram")


    Homo sapiens

    78. What is polymorphism in Python?

    Polymorphism in Python 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 other implementations. For instance, the + operator performs addition for integer objects and concatenation for string objects.

    79. What is encapsulation in Python?

    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.

    80. What is data abstraction in Python?

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

    81. What are Dunders in Python?

    Dunders stands for double underscores , and these are the special magic methods used in Python that have two 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__.

    82. Does Python have access specifiers?

    Python does not have the concept of access specifiers. Still, developers use some naming conventions in Python to specify private, public, and protected members.

    • We put a single underscore (_) before the member name to create a private member in the Python class.
    • We use the double underscore (__) before the member name to create a protected member.
    • And for a public member, we do not need to put any underscore before the member name.

    By default, in the Python class, every member is public, and even after defining the members as private or protected according to the naming convention, these members are still treated as public members by Python.

    Example :

    class A:
        _private =  10
        __protected = 20
        public = 30
    class B(A):
    b = B()
    #access all the private protected and public members of A using B object
    print("Private", b._private)        #10
    print("Protected", b._A__protected) #20
    print("Public", b.public)           #30 

    Double underscores before the member name are used for name mangling. Let's say the base and the derived class have the same variable names. We can separate the base class and derived class variables using double underscores. You can see that to access the protected member of class A using the class B object, we put class A before the protected name.

    Python Interview Questions for Experienced Developers

    We have discussed only the basic Python interview questions, i.e., Python interview questions for freshers. This is because, in most Python interviews, the interviewer first checks the basic Python skills of the candidate. Once the interviewer feels that the candidate understands the Python basics, 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:

    83. Why is this statement often used in Python: if __name__==”__main__”:?

    __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 being imported. If the file runs directly, the __name__ variable will automatically be 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 will return false.

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

    The open() function opens a text file for reading, writing, and appending purposes. It accepts two parameters: the filename that needs to be opened and the file's mode of opening.

    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:


    85. What is Python GIL?

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

    86. Can we do multithreading in Python?

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

    87. What does the global keyword do in Python?

    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, 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
    print("Now the value of  g_var is:", g_var)


    Now the value of  g_var is: 300

    88. What does the nonlocal keyword do in Python?

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


    def outer_function():
        count =200
        def nested_function():
            nonlocal count  # it will grab the count variable of its outer scope
            count +=100
            return count
        print("The value of count is: ", count)


    The value of count is:  300

    89. What are context managers in Python?

    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 file handling code, we have first to write the open() statement to open the file, then write some code to read and write between the file, and last, we have to mention the close() method to close the file.

    This complete process is prone to exceptions, and developers often 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 far more efficiently.


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

    90. What is CPython?

    CPython is the default implementation of the Python programming language. Python we install from the official website is CPython. This is called CPython because it is written in the C programming language.

    >>>import platform
    >>> platform.python_implementation()

    91. What is monkey patching in Python?

    Monkey patching in Python is also known as a dynamic or runtime modification. We can modify a class and its module with monkey patching in Python during runtime.


    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()


    function method

    Python Libraries/Framework Interview Questions

    Libraries and frameworks are the main assets of the Python programming language. Python supports many popular libraries and frameworks for web development and data analysis. As a Python developer, you should briefly know the popular Python libraries and frameworks like Flask, Django, pandas, numpy, and so on.

    92. How can Python be used for web development?

    Python is well known for its web frameworks. A web framework 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.

    93. What is Django?

    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.

    94. What is Flask?

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

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

    Flask is a microframework generally used to develop small web applications requiring additional libraries.

    Pyramid is more giant than Flask, and that’s why it is used for building big web applications. It allows developers to work with databases, templates, and URL structures.

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

    96. What are virtualenvs in Python?

    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

    97. Name some of the widely used Python inbuilt modules.

    1. os: This module deals with operating system functionality like file management using Python.
    2. math: To perform mathematical computation, we can use the math module.
    3. sys: To write system-related programs with Python, we can use the sys module.
    4. re: For regular expression, re module, provides many inbuilt methods.
    5. datetime: To handle date and time data in Python, we can use the datetime module.
    6. JSON: To read the JSON data.
    7. random: To generate and play with random numbers.

    Python Web Scraping Interview Questions

    Web scraping with Python is one of the basic applications of Python. The popular programming language supports many built-in and third-party libraries, like requests, Beautifulsoup, scrapy, and so forth, that can scrape any data from web pages. In a Python interview, you may face some questions from web scraping, so you should prepare better.

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

    url =""
    import urllib.request
    urllib.request.urlretrieve(url, "local-image.jpg")

    99. Write a Python program to scrape the top 20 movies from IMDb Top 250 Movies.

    from bs4 import BeautifulSoup
    import requests
    #url to the imbd top movies
    response = requests.get('')
    soup = BeautifulSoup(response.content, 'html.parser')
    #to get the top 20 movies
    movies = soup.find_all('td',"titleColumn")[:20]
    #print the movies
    for movie in movies:
        print(" ".join(movie.text.split()))

    Python Numpy Interview Questions

    100. What is NumPy?

    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 ten times faster than the standard Python list.

    101. What are the advantages of using numpy arrays over a Python list?

    The Python list does not fully fill the concept of arrays in Python. An array data structure is faster and more compatible with arithmetical computation, whereas a Python list is not. The Numpy arrays are more inclined toward storing and dealing with numerical data types.

    Like a normal array concept, the Numpy array supports arithmetical computation. As the data increases, the size of the array increases simultaneously. Still, the performance of a numpy array is always 30 times faster than a Python list. This is because the numpy array only deals with homogenous data types, and the data type of every item is declared during the creation of the array.

    102. Create 1D, 2D, 3D, and nD arrays using numpy.

    1. Create a 1D array

    import numpy as np
    oneD = [1,2,3,4]
    oneDArray = np.array(oneD)
    print("1D Array:", oneDArray)

    2. Create a 2D array

    import numpy as np
    twoDArray = np.array(twoD)
    print("2D Array  : ",twoDArray)

    3. Create a 3D array

    import numpy as np
    threeDArray = np.array(threeD)
    print("3D Array : ",threeDArray)

    4. Create an nD array

    import numpy as np
    #create a 5D array of 2 items in each direction
    nDArray = np.random.rand(2,2,2,2,2)
    print('N Dimensions of array:', nDArray)

    103. You have given a 3X3 matrix, and you need to remove the second column data from each row and add a new 2nd column to the matrix.

    import numpy as np
    #given matrix
    given_matrix= [
    new_col = np.array([[20,50,80]])
    #convert given array to numpy matrix
    matrix = np.array(given_matrix)
    # delete the second column
    matrix = np.delete(matrix , 1, axis = 1)
    #insert the new column to the matrix
    matrix = np.insert(matrix , 1, new_col, axis = 1)
    print (matrix)


    [[ 1 20  3]
     [ 4 50  6]
     [ 7 80  9]]

    104. How to read and convert CSV data into a numpy array?

    We can use the getfromtxt() method to read and convert the CSV data into a numpy array.


    import numpy as np
    array = np.getfromtxt('file.csv', delimiter=",")

    105. You have given an integer matrix of 4X4, and you need to write a Python script that can sort the matrix based on the 3rd column.

    import numpy as np
    #matrix of 4X4
    matrix = np.array([
                        [10, 36, 84, 48],
                        [35, 84, 95, 26],
                        [44, 84, 76, 90],
                        [78, 56, 43, 23]
    print("Original Matrix")
    #sort the matrix based on 3rd column
    matrix = matrix[matrix[:,2].argsort()]
    print("Sorted Matrix by 3rd column")


    Original Matrix
    [[10 36 84 48]
     [35 84 95 26]
     [44 84 76 90]
     [78 56 43 23]]
    Sorted Matrix by 3rd column
    [[78 56 43 23]
     [44 84 76 90]
     [10 36 84 48]
     [35 84 95 26]]

    106. Write a Python program that finds the nearest value for a given number from a given numpy array.

    With the help of the argmin() method, we can find the nearest value for a given number from a numpy array.

    import numpy as np
    def nearest_value(arr, value):
       arr = np.asarray(arr)
       i = (np.abs(arr - value)).argmin()
       return arr[i]
    if __name__=="__main__":
        #given array
        arr = np.array([ 0.324,
        given_value = 0.674
        print(f"The nearest value to {given_value} in array is:", end="")
        print(nearest_value(arr, given_value))


    The nearest value to 0.674 in array is:0.634

    107. How to reverse a Python numpy using a single line of code?

    import numpy as np
    if __name__=="__main__":
        #given array
        arr = np.array([ 0.324,

    108. How to find the dimensions of a numpy array?

    To find the dimensions or shape of the numpy array, we can use the shape property on the array, and it returns a tuple of integer numbers representing the dimension and the row and column count of the array.

    Example :

    import numpy as np
    if __name__=="__main__":
        arr2D= np.array([[1,2,3,4],
        arr1D = np.array([1,2,3,4,5,6,7,8])
        print("The shape of 1 D array is:", arr1D.shape)
        print("The shape of 2 D array is:", arr2D.shape)


    The shape of 1 D array is: (8,)
    The shape of 2 D array is: (2, 4)

    Python Pandas Interview Questions

    pandas is one of the most powerful and widely used Python data analysis libraries . It features many complex and robust methods and properties for complex computations. In Python interviews, the interviewer often asks questions related to the pandas DataFrame and series, which are pandas' most used data structures. Here are some of the frequently asked Python Pandas interview questions.

    109. What do you know about pandas in Python?

    • Pandas is an open-source Python library widely used for data manipulation and analysis.
    • Similar to the numpy arrays, it supports more powerful series and data frames.
    • We can use the pip install pandas command to install pandas for a Python environment.
    • Pandas provide many powerful built-in methods and properties for data analysis.

    110. What is dataframe in pandas?

    Dataframes in pandas is more similar to the 2D arrays. The key difference between the numpy arrays and dataframes is that in every dataframe, numpy arrays are labeled with index numbers, but data frames can be labeled with some string data.

    Example :

    import pandas as pd
    data = {'Name':['Rohan', 'Sam', 'Rose', 'Yug' ],
    #convert the data into data frame
    df = pd.DataFrame(data)


        Name  Salary  Age
    0  Rohan    2343   45
    1    Sam    5634   35
    2   Rose    2557   37
    3    Yug    4647   38

    111. How to combine two dataframes in Python?

    There are three methods in Python pandas to combine two dataframes.

    1. append() Using the append() method on a data frame, we can add new rows of data to the existing dataframe. In short, using the append() method, we can combine two data frames horizontally.


    import pandas as pd
    df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
    df2 = pd.DataFrame([[5,6], [7,8]], columns= ['A', 'B'])
    #combine df1 and df2 using append


       A  B
    0  1  2
    1  3  4
    0  5  6
    1  7  8

    2. concat() Using the concat() method, we can concatenate two pandas dataframes on a particular axis.

    import pandas as pd
    df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
    df2 = pd.DataFrame([[5,6], [7,8]], columns= ['C', 'D'])
    #concatenate along column
    print(pd.concat([df1,df2], axis=1))


       A  B  C  D
    0  1  2  5  6
    1  3  4  7  8

    3.  join() Using the join method, we can add one dataframe with another on the index or key column.


    import pandas as pd
    df1 = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
    df2 = pd.DataFrame([[5,6], [7,8]], columns= ['C', 'D'])
    #join along coloumn
    print(df1.join(df2, lsuffix='_', rsuffix='_'))


       A  B  C  D
    0  1  2  5  6
    1  3  4  7  8

    112. Create a Pandas series using a dictionary in Python.

    A series is a one-dimensional array in pandas. To convert a dictionary object to a series, we can use the Series() method.

    import pandas as pd
    #dictionary object
    dict_data = {'a':1, 'b':2, 'c':3, 'd':4}
    #series object
    s = pd.Series(dict_data)


    a    1
    b    2
    c    3
    d    4
    dtype: int64

    113. How to count the number of missing values in a dataframe?

    Check for the missing values or null values in a data frame. To do so, we can use the isnull() method, and by applying the sum() method to it, we can count the number of missing values.


    import pandas as pd
    #missing null values
    null_count = df.isnull.sum()

    114. How to replace the null values of dataframes with zero.

    Using the fillna() method, we can replace all the null values of the dataframe with 0.



    To replace all the NAN values of a specific column with 0, we can run the fillna() method on the specific column.



    Python Coding Interview Questions

    Often during a Python interview, 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, write a Python program to solve a problem or implement some data structures using Python. Here are some of the most frequently asked Python coding interview questions:

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



    116. What would be the output of this code?




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

    [3, 4, 5]

    118. What would be the output?

    for i in range(4):


    [2, 4, 6]

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



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

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

    print(Lis1 is Lis2)



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


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




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

    if a==b:



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

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

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

    if id(lis1)==id(lis2):



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



    [1, 2, 3]

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




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

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



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

    if lis[1]in lis[0]:


    130. What would be the output?


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

    131. Name the type of error for this syntax:

    l = "hello world"

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

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

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

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

    133. Write a Python program to delete a file in the same directory as the Python script.

    Using the python os module and the .remove method, we can delete the file from our system as shown below:

    import os

    134. Implement bubble sort in Python.

    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())
    for k in range(len(arr)):
        for i in range(0, num-k-1):
            if arr[i] > arr[i+1]:
    for i in range(len(arr)):
        print(arr[i],end=' ')

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

    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):
        now = first + second
        first = second
        second = now


    How many numbers you want to pick from the Fibonacci series: 7
    Fibonacci sequence:

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

    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")
        print(num,"is not a prime number" )


    Enter a Number:1313 
    1313 is a prime number

    137. Write a Python program to check whether a sequence is a palindrome.


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


    Enter the String:daddad
    daddad is a palindrome string

    Python Multiple-Choice Questions

    138. What is the maximum length to name a Python identifier?

    a) 16 b) 32 c) 64 d) No fixed length


    139. What will be the output of the following code snippet?

    if 0:

    a) True b) False c) Nothing will be printed d) None

    b) False because 0 is treated as a False value by the if else statement.

    140. What will be the output datatype for the following code snippet?


    a) tuple tuple int b) list tuple int c) tuple int tuple d) tuple int int

    d) tuple int int

    141. How to represent the code block in Python

    a) Using Brackets b) Using Indentation d) Using Key e) Using Parenthesis

    b) Using Indentation. The indentation could be spaces or tabs.

    142. What will be the output of the following code snippet?

    a = [10, 20, 30]
    a = tuple(a)
    a[1] = 100

    a) (10, 100, 30) b) [10, 100, 30] c) (10, 20, 30) d) Error

    d) Error

    143. What will be the output of the following code snippet?


    a) int float b) int int c) float int d) float float

    a) int float

    144. What will be the output of the following code snippet?

    def func():
        global x
        x = 20
    x = 30


    a) 20 b) 30 c) None d) None of the Above

    a) 20

    145. Which of the following statement is used for exception handling in Python?

    a) try b) except c) finally d) All of the above

    d) All of the above are used for exception handling in Python .

    146. What will be the output of the following code snippet?

    a,b = 30, 40
    a,b = b, a

    a)  30 40 b) 40 30 c) 30 30 d) None of the above

    b) 40 30

    147. Which of the following loops does Python not support?

    a) for b) while c) do while d) None of the above

    c) do while

    148. What will be the output of the following code snippet?

    def func(num):
        print("ODD" if num%2==0 else "EVEN")

    a) ODD b) EVEN c) None d) None of the above

    a) ODD

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

    x = [47, 20, 31, 12]

    a) [47, 31, 20, 12] b) [12, 20, 31, 47] c)  None d) None of the Above

    c) None because the list sort() method returns None. Moreover, it performs in-place sorting on the existing list.

    150. What data type will be output for the following code snippet?

    x = (47, 20, 31, 12)
    x = sorted(x)

    a) list b) tuple c) set d) NoneType

    a)list. This is because the sorted() method sorts the iterator object items in lexicographical order and returns them and a list.

    Python Competitive Programming Interview Questions

    In interviews to test the programming skills of Python developers, interviewers often make them solve some competitive programming questions. Here is a list of some of the frequently asked Python Competitive Programming interview questions.

    151. Implement the fizzbuzz problem in Python.

    for i in range(51):
        if i % 3 == 0 and i % 5 == 0:
        elif i % 3 == 0:
        elif i % 5 == 0:

    152. Write a Python program that prints all the subarrays of sum 0 from a given array.

    Solution .

    153. Write a Python program to find a triplet with the maximum product in an array.

    Solution .

    154. Write a Python program that finds the minimum index of a repeating element in an array.

    Solution .

    155. Write a Python program that finds a pair with an absolute minimum difference in an array.

    Solution .


    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, etc.

    All the Python interview questions we have provided here cover most of the core Python concepts with some advanced Python libraries.

    For instance, if you have a Django interview, we recommend reading the Python interview questions and then the Django interview questions . This will help you to refresh your Python and Django skills.

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

    Thanks already!

    People are also reading:


    As Python is a general-purpose programming language, it is used for a variety of purposes, along with software development. Data scientists, data analysts, web developers, software developers, AI engineers, and machine learning engineers are some popular job roles that require you to have proficiency in Python programming.

    A Python developer is a skilled person who leverages the Python language and related frameworks, libraries, IDEs, and other development tools to create software as well as web applications.

    To become a Python developer, you must develop expertise in Python, a good grasp of web frameworks, Object Relational Mappers (ORM), data science, AI, ML, and deep learning, have a good understanding of multi-process architecture, Python shell, and front-end technologies, and good communication skills.

    Yes, Python is among the easiest languages to learn. It is a beginner-friendly language having a low learning curve. The syntax of Python is extremely simple and contains simple English keywords.

    According to glassdoor, the average salary of an entry-level Python developer in India is INR 4.5 lakhs per annum. Meanwhile, Python developers in the United States earn a median salary of $1 lakh per year.

    Leave a Comment on this Post