154+ Top Python Interview Questions and Answers

Posted in /   /  

154+ Top Python Interview Questions and Answers

Vinay Khatri
Last updated on November 9, 2022

    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 basic concepts clear.

    Do you want to learn Python from scratch and master it? Get started here .

    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 will help you to crack the interview.

    Top Python Interview Questions and Answers

    The Python interview questions and answers are classified into the following categories:

    1. Basic Python Interview Questions
    2. Intermediate Interview questions
    3. Python Coding Interview Questions
    4. Python OOPS Interview Questions

    Basic Python Interview Questions (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 Python interview questions, you face problems with 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. Is Python a scripting language or a programming language?

    Answer: The key difference between scripting and programming languages is that a scripting language does not require the additional step of compilation, 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 gets executed. According to the definition of scripting and programming language, Python comes in the league of scripting languages, but in a general sense, Python is introduced as a high-level programming language.

    4. What is PEP 8 in Python?

    Answer: 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 a legible Python code. Some of the important code writing styles defined in PEP 8 are:

    • There should be 4 spaces per indentation level.
    • Spaces and tabs can both 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?

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

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

    8. How is Python 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. Thus, by 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

    9. What is the purpose of the pass keyword? 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.

    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

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

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

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

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

    14. What are dictionaries in Python?

    Answer: Python dictionaries are the collections of key 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

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

    Answer: No, the keys of a 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.

    16. Write 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) 17. 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’>

    18. 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'>

    19. 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 has 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

    20. What is a lambda function in Python?

    Answer: A 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)

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

    Answer:

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

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

    Example:

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

    Outputs

    5
    4

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

    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'

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

    25. How can we import modules in Python?

    Answer: There are three methods we can use 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?

    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 the Python programming language. 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])

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

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

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

    Answer: range() is a special function in Python. It is used to iterate over a number of sequences. The range() function can accept three 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

    30. What are dictionaries in Python, and how are they 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.

    31. 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”]

    32. Does python have a compiler?

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

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

    34. Explain the map() function in Python?

    Answer: map() is an inbuilt Python method that takes two 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 useful 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]

    35. 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]

    36. Does Python support procedural programming?

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

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

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

    39. 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)

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

    41. 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. However, using the pass keyword, we can declare a function and later define it.

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

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

    44. If a break statement is used inside the nested loop, then which loop will it 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

    45. What does the continue keyword do in python?

    Answer: 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:
            continue
    print(i)

    #output

    0
    1
    2
    3

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

    Answer:

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

    Code Example:

    >>> ord("a")
    97
    
    >>> chr(98)
    'b'

    47. What does the 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

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

    49. 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 the rest of the string lowercase.

    Code Example:

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

    50. 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)

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

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

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

    53. What is list comprehension in Python?

    Answer: In Python, 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]

    54. What does the 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)

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

    Answer: Random Library.

    Code Example:

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

    Output 3

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

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

    58. How are errors 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.

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

    60. 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!

    61. 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 loop. To create a generator, we use functions and a special statement called yield . In simple words, generators are the functions that yield 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

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

    63. 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 statement does not.

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

    Answer: @my_dec

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

    66 What is a docstring in Python?

    Answer: Docstring in Python means documentation string, and it is used to provide some additional information regarding the Python modules, functions, classes and methods.

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

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

    69. What does the del keyword do in Python?

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

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

    Answer: KeyError.

    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?

    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

    72. 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')

    73. How to create an empty class in Python?

    Answer: 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. Example:

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

    74. What is the __init__ method?

    Answer: The __init__() method is a reserved method of a class. 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):
            pass
    dog=Animal() #instance of a class

    Output

    I am an Animal

    75. 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 the Human class

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

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

    78. What is polymorphism in Python?

    Answer: 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 different implementations. For instance, the + operator performs addition for integer objects and concatenation for string objects.

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

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

    81. What are Dunders in python?

    Answer: 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, there are some naming conventions in Python that developers use to specify private, public, and protected members.

    • To create a private member in the Python class, we put a single underscore (_) before the member name.
    • To create a protected member, we use the double underscore (__) before the member name.
    • 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 the Python.

    Code Example :

    class A:
        _private =  10
        __protected = 20
        public = 30
        
    class B(A):
        pass
    
    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 

    The double underscores before the member name are used for name mangling. Let's say if the base and the derived class have the same variable names. Using the double underscores, we can separate the base class and derived class variables. 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

    By far, 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 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:

    83. Why is 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 will return false.

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

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

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

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

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

    89. 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 prone to exceptions, 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()

    90. What is CPython?

    Answer: CPython is the default implementation of the Python programming language. 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'

    91. 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 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, and as a Python developer, you are supposed to have a brief knowledge of the popular Python libraries and frameworks like Flask, Django, pandas, numpy, and so on.

    92. How can Python 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.

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

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

    95. 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, and 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.

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

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

    A :

    1. os: This module is used to deal with the 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 the web pages. In a Python interview, you may face some questions from web scraping, so you should better go prepared.

    98. 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")

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

    Answer:

    from bs4 import BeautifulSoup
    import requests
    
    #url to the imbd top movies
    response = requests.get('https://www.imdb.com/chart/top/')
    
    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?

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

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

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

    Answer: 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
    twoD=[[10,20,30],[40,50,60]]
    twoDArray = np.array(twoD)
    print("2D Array  : ",twoDArray)

    3. Create a 3D array

    import numpy as np
    threeD=[
            [
                [1,2,3],
                [4,5,6],
                [7,8,9]
             ]
            ]
    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.

    Answer

    import numpy as np
    
    
    #given matrix
    given_matrix= [
                    [1,2,3],
                    [4,5,6],
                    [7,8,9]
                   ]
    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)

    Ouput

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

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

    Answer: To read and convert the CSV data into a numpy array, we can use the getfromtxt() method.

    Code Example:

    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.

    Answer

    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")
    print(matrix)
    
    #sort the matrix based on 3rd column
    matrix = matrix[matrix[:,2].argsort()]
    
    print("Sorted Matrix by 3rd column")
    print(matrix)

    Output

    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 out the nearest value for a given number from a given numpy array.

    Answer: 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,
                         0.634,
                         0.464,
                         0.845,
                         0.936,
                         0.543,
                         0.497])
        given_value = 0.674
        print(f"The nearest value to {given_value} in array is:", end="")
        print(nearest_value(arr, given_value))

    Output

    The nearest value to 0.674 in array is:0.634

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

    Answer:

    import numpy as np
    
    if __name__=="__main__":
        #given array
        arr = np.array([ 0.324,
                         0.634,
                         0.464,
                         0.845,
                         0.936,
                         0.543,
                         0.497])
        print(arr[::-1])

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

    Answer: 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. Code Example :

    import numpy as np
    
    if __name__=="__main__":
        arr2D= np.array([[1,2,3,4],
                         [5,6,7,8]])
    
        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)

    Output

    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. Often in Python interviews, the interviewer asks some 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?

    Answer:

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

    110. What is dataframe in pandas?

    Answer: Dataframes in pandas are 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 the index numbers, but data frames can be labeled with some string data.

    Code Example :

    import pandas as pd
    
    #dataframe
    data = {'Name':['Rohan', 'Sam', 'Rose', 'Yug' ],
            'Salary':[2343,5634,2557,4647],
            'Age':[45,35,37,38]
            }
    
    #convert the data into data frame
    df = pd.DataFrame(data)
    
    print(df)

    Output

        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?

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

    Example

    import pandas as pd
    
    #dataframes
    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
    print(df1.append(df2))

    Output

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

    Output

       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, either on the index or key column.

    Example

    import pandas as pd
    
    #dataframes
    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='_'))

    Output

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

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

    An : 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)
    
    print(s)

    Output

    a    1
    b    2
    c    3
    d    4
    dtype: int64

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

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

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

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

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

    Example

    df.fillna(0)

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

    Example

    df['column'].fillna(0)

    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 or 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?

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

    Answer: 40

    116. What would be the output of this code?

    print("5"*4)

    Answer: 5555

    117. 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]

    118. 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]

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

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

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

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

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

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

    Answer: None

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

    print(bool(3<4)*20)

    Answer: 20

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

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

    Answer:

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

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

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

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

    Answer: [1, 2, 3]

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

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

    Answer: 3

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

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

    Answer: Hello

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

    130. What would be the output?

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

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

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

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

    133. 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 as shown below:

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

    134. 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=' ')

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

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

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

    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

    Answer: d

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

    if 0:
        print("True")
    else:
        print("False")

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

    Answer: 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?

    print(type((0,1,2,3,4)))
    print(type((0)))
    print(type(1))

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

    Answer: 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

    Answer: 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
    print(a)

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

    Answer: d) Error

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

    print(type(2//3))
    print(type(2/3))

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

    Answer: a) int float

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

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

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

    Answer: 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

    Answer: 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
    
    print(a,b)

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

    Answer: 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

    Answer: 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")
    
    func(4)

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

    Answer: a) ODD

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

    x = [47, 20, 31, 12]
    
    print(x.sort())

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

    Answer: 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)
    
    print(type(x))

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

    Answer: 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

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

    151. Implement the fizzbuzz problem in Python.

    Answer:

    for i in range(51):
        if i % 3 == 0 and i % 5 == 0:
            print("fizzbuzz")
        elif i % 3 == 0:
            print("fizz")
        elif i % 5 == 0:
            print("buzz")
        else:
            print(i)

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

    Answer: Solution .

    153. Write a Python program that can find a triplet having the maximum product in an array.

    Answer: Solution for the maximum product in an array.

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

    Answer: Solution .

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

    Answer: Solution .

    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 the 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!

    For more Python interview questions, you can buy the course here.

    People are also reading:

    FAQs


    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

    0 Comments