Python Interview Questions

By | October 29, 2020
Python Interview Questions

Python is one of the most versatile and powerful programming languages. It has a very bright future and promises many opportunities for its developer. So, whenever you apply for a job as a Python Developer, you have to face the Python interview where the interviewer will test your python skills. It has often seen that during the interview interviewer asks questions from core python and candidate not able to answer those. So it always recommended that make your basics concepts reliable. Here in this article, we have provided the Top 100 Python Interview questions, which are frequently asked during python Interviews. We hope these Python Interview questions and answers would help you to crack the interview.

Best Python Interview Questions

Basic Python Interview questions

In mostly all the Python interviews the interviewer will first check your Python basic knowledge based on core Python Programming. In the basic Python interview, you face problems from Python core syntax and Python data structure. On the basis of your answer, the interview will estimate your python skills and may further ask you Python intermediate and advance questions related to your answer.

Vamware

Let’s first have a look at some of the Python interview questions for freshers.

Question: What is Python?
Answer: Python is the most popular, high-level, object-oriented, interpreted programming language. It’s easy to read and learn syntax make it one of the easiest programming languages and it also reduces its program maintenance cost.

Question: What do you mean by interpreted programming language?
Answer: An Interpreted programming language is a type of Programming language which uses an interpreter to execute the program code. And in an interpreted programming language the code gets directly executed without compiling into a machine language code.

Question: Name some main Features of Python for which it is Popular.
Answer:

  1. It supports the Functional and structured Programming language, which also follows the concepts of OOP’s.
  2. It is a dynamic language.
  3. It has a feature of Automatic Garbage collection.
  4. It is very easy to interpret.

Question: Tell some benefits of Python.
Answer:

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

Question: How Python is a Dynamic 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. The Python binds the value with the variable name and stores the value at the memory location. And using the variable name we can access the value of the variable and we can also change the value and data type of the variable throughout the program.

E.g.

var1=10 # var1 is an integer type

var2 ="Hello world" # var2 is a string

Question: What pass keyword do and why do you use it?
Answer: The pass is a special keyword in the 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 them, the python interpreter will through an error. To overcome this error, you can use the pass keyword inside the if and functions statements.

e.g.

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

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

  1. Numbers in Python represent the numeric value.
  2. Strings in python represent the sequence of characters inside the double and single quotes.
  3. List is an ordered and mutable data structure that can store multiple data values.
  4. Tuples is an ordered, and immutable python data structure that can store multiple data values.
  5. Dictionaries is an unordered and mutable python data structure that stores elements in the form of key:value pair.
  6. Sets is an unordered and mutable python data structure that only contain unique element value.

Question: What are Mutable and Immutable Datatypes
Answer:

  • Mutable are those data types in python whose value can be changed.e.g.list, Dictionaries, and Sets
  • Immutable are those data types once they have been assigned you cannot manipulate their values.e.g.Strings, Tuples and Numbers

What are the sets in Python?
Answer: Sets are the unordered collections of data values that are immutable and do not accept the repetitive values. sets are iterable object but do not accept indexing.

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

Output:

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

Question: What are tuples in Python?
Answer: Tuple is an ordered and immutable Python inbuilt data structure Tuple can store heterogeneous elements but it is generally used to store heterogeneous data elements. Like a list tuple also supports indexing and slicing to retrieve elements.

e.g.

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

Output

3

Question: What are Dictionaries in Python?
Answer: Python Dictionaries are the collections of keys and value pairs separated by a colon. A dictionary key can only be represented by an immutable data type whereas a value could be of any data type.

E.g.

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

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

Question: Write a code to convert 144 into a string
Answer: To convert any data object or value to a string, we can use the Python str() method.

str(144)

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

e.g.

def arg(*args):
    print(args)
    print(type(args))

arg(1,2,3,4,5,6,7,8)

Output

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

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

e.g.

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

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

Output

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

<class 'dict'>

Question: What does the end statement do in python?
Answer: Whenever we use a print() method to print a statement the statement printed on a new line. The end is an additional parameter of the print() method which have a value of ‘\n’ by default that’s why every print() statement print on 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.

e.g.

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

Output

hello world
go for-it

Question: What is a lambda function in Python?
Answer: Lambda function in Python is also known as an anonymous function. An anonymous or 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.

e.g.

# Normal function in python

def mul(a,b):
    return a*b

mul(10,20)

#lambda function
mul=lambda a,b : a*b
mul(10,20)

Question: What is the difference between Python list and Python tuple?
Answer: 

Python list Python Tuples
Python list is a mutable data structure Python tuples are immutable data structure.
List consume more memory space as compared to tuples 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 Python tuple.
List support more methods as compared to tuple. Tuple does not have many in-built methods.
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.

e.g.

list1=[0,1,2,3,4] #list

tuple1=(0,1,2,3,4) #tuples

list1[2]=4 #Mutable

tuple1[2]=4 # it will through an error because tuples are immutable

Question: What is negative indexing in python?

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

e.g.

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

print(list1[-1])

print(list1[-2])

Outputs

5
4

Question: What are the Exceptions in Python?
Answer: Exception in Python are the errors which generally occur during the runtime. FileNotFoundError, ZeroDivisionError, ValueError and ImportError, are some of the most common 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'

Question: How can we raise an Exception in Python
Answer: In Python, we have the raise keyword which can be used to raise the error in a Program.

print(" hello ")

raise ValueError

print(" world ")

Output

hello

ValueError

Question: How can we import modules in Python?

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

import numpy #this import the numpy module

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

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

Question: Does Python have a concept of inbuilt Array?
Answer: However, Python does not have inbuilt support for Array Data structure, like it supports list, set, tuple, and dictionary. But python-support an inbuilt module array which provides an array data structure for python. The Python array module is not that much efficient and that’s why developers always prefer to use numpy array.

Example

import array

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

Question: Name all the type conversion methods present in Python.

Answer:

Type conversion method Description
int() convert the object into integer
float() convert the object into floating point number
list() convert the object into list
dict() convert the object into dictionary
tuple() convert the object into tuple
str() convert the object into string
ord() convert the character into corresponding ASCII value.
chr() Convert the ASCII value to character.
oct() convert the integer to octal value
complex(real, imag) convert the integer value to complex number.
hex() convert the integer value to hexa decimal.

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

Example

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

Output

30
70

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

e.g.

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

Output

2
4
6
8

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

Dictionary syntax:

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

Python list Python dictionary
Python list is an ordered data structure. Python dictionary is an unordered data structure.
In list, we use indexing to access the individual element. In dictionary, we use the key name to access the individual element.
To initialize a list, we use the square brackets To initialize a dictionary, we use curly brackets.
List occupies less memory as compared to a dictionary. A dictionary occupies more memory as compared to a list

Question: 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 string, but using slicing we can retrieve a sequence of elements.

e.g:

# List slicing

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

print(lis[2:6])

print(list[3:8:2])

Outputs

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

Question: Does python have a compiler?
Answer: Yes, python does have the compiler. It’s works automatically.

Question: What is an index in python?
Answer: In python to retrieve a specific value from a list, sting, or tuples we use the index. An Index is an integer that starts from 0 and up to n-1, where n represents the total number of elements present in the data structure.

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

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]

Question: Explain 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.

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

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

print(res)

Output

[10,24]

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

Question: What is a function in Python?
Answer: A function is a set of code that is used to perform a specific task. the function helps us to enhance the reusability of code. In python to declare a function, we use a def keyword.

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

  1. Built-in functions (functions already provided by the python)
  2. User-defined functions

Question: What are the Local variables?
Answer: When a variable is assigned inside a function is known as Local variable and only that specific function is allowed to use that variable.

Example

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

Question: What are the global variables?
Answer: All those variables which are not defined inside a function are known as a global variable and any function can access a global variable.

Example

global_var =70

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

#output 

30

Question: If we declare a function and do not define it what will happen?
Answer: If we only declare a function and do not define its body then the python interpreter will throw an error. But using the pass keyword we can declare a function and later define its body.

Question: If a Python function does not have a return statement then what it returns?
Answer: If a function does not have a return statement then it returns None.

Example

def func():
    a =20

print(func())

Output

None

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

e.g.

#break syntax

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

Output

0
1

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

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

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

#continue syntax

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

#output

0
1
2
3

Question: What ord() and chr() methods do in python?
Answer: 

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

e.g.

>>> ord("a")
97

>>> chr(98)
'b'

Question: What does isaplha() method do in python?
Answer: isalpha() is a string method that checks if the string contains only alphabets. If the string contains only alphabets the method will return true else it will return False.

e.g.

print(“Hello”.isalpha())

print(“Hello 2”.isalpha())

Output

True

False

Question: What does a split() method do in Python?
Answer: split() is a Python string method that split a string into a list of words. By default, the split function split the string into list values by using the white space.

e.g.

str=’hello world I am here’

print(str.split())

print(str.split(‘e’))

Output

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

Question: What is the difference between title() and capitalize() methods in Python?
Answer: 

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

Example

>>> title = "this iS a TiTlE"

>>> title.title()

'This Is A Title'

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

Example

>>> title = "this iS a TiTlE"

>>> title.capitalize()

'This is a title'

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

E.g.

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

Question: What dir() method do in Python?
Answer: The dir() method can return all the properties and methods of an object. With the help of dir() the method, we can find out all the properties a method supported by an object.

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

Question: In python how can we use third-party libraries?
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.

 Question: What is list comprehension in python?
Answer: A list comprehension is a method of creating a new list from an iterable object(list, tuple, set, etc). List comprehension provides an elegant and one line technique to create a list out of the iterable object.

E.g.

#List comprehension Syntax:

old_list=[1,2,3,4,5,6]

new_list=[i*2 for i in old_list]

print(new_list)

Output

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

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

e.g.

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

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

Answer: Random Library

e.g.

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

Output

3

Question: What is recursion 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 the recursion fall in an infinite call.

e.g.

#Recursion Syntax in python

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

print(fac(3))

Output

6

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

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

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

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

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

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!

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

#Generator Syntax

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

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

Output

4
3
2
1

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

Question: How the yield statement is different from the 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 cannot.

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

Question: What is a floor division?
Answer: It is similar to the normal division but it returns the floor integer value of the quotient.

e.g.

print(6//9) #floor division

print(6/9) # Normal division

Output

0
0.6666666666666666

Question: What is NumPy?
Answer: NumPy is one of the most popular Python libraries, it stands for numerical python and commonly used in Python Data Science. It comes with many powerful built-in methods and NumPy array is one of those. A NumPy array is 10 times faster than the Python list.

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

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

e.g.

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

#output
35

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

e.g.

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

def mul(n):
    return n*2

print(fun1(mul,10))

Output

40

Question: What does del keyword do in python?
Answer: The del the keyword is used to delete the object from the memory.

Python Intermediate and experienced  Interview Questions

By far we have discussed only the Python interview questions for the freshers because in most of the Python interviews the interviewer first checks the basic Python skills of the candidate. Once the interview feels that the candidate’s basic Python skills are strong then he/she starts asking some intermediate and advanced Python interview questions. Now let’s look at some of the Python interview questions for an experienced developer.

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

The __name__==”__main__” statement will return True if the file is executed directly, if this file is imported the __name__==”__main__” statement return False.

Question: What is Python GIL?
Answer: GIL stands for Global Interpreter Lock, and it is a muter or lock which 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.

Question: Can we do multithreading in Python?

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

Question: What is Polymorphism in Python?

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

Question: 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 OOP’s encapsulation.

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

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

 Question: Name some tools which can be used to find a bug in Python

Answer: 

PyChecker is one of the open-source static analysis tool, which can be used to find the bug in a Python source code.

Pylint is another very popular python debugger tool that can warn us about the bugs and error present in the Python source code.

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

Syntax

filter(predicate, iter)

Example

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

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

Output

[10,24]

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

e.g.

print("hello")

assert 2+2==4

print("world")

assert 2+2==5  #error

print("world")

Output

helloworld 
AssertionError

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

The try block represents the part of code that may contain error or through error during runtime and the except block represent the code what to do if there is an error in the try block. The except block get executed if there is an error in the try block.

#syntax for trying and execute statements

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

Output

hello world
there is an error in the above statement

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

import os
print(os.__file__)

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

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

Question: What is the difference between shallow and deep copy in Python?

Answer:

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

Example

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

new = old.copy()   #shallow copy

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

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

Output

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

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

Example

import copy

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

new = copy.deepcopy(old)

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

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

Output

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

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

Question: Write all errors that occurred in python.
Answer:

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

Question: Explain the .py and .pyc file extension.
Answer: the .py is the file extension of the Python program, and .pyc is the file extension of the compiled byte code file which is generated by python.

Question: What are the module and packages in Python?
Answer: Module: Module is the Python Program file that can be imported to other python Program by using the import keyword

Packages: Packages are the folders which contain a bunch of python module and subfolders. Subfolders also contain modules.

Question: 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. In Python to create a class, 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

Question: 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 using the class keyword in python we can define our own methods and properties.

e.g

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

Question: What is an __init__ method?
Answer: __init__() method is a reserved method of a class and it is also known as the constructor of a class. Whenever you initialize an instance of a class the __init__() method of the class automatically get called.

E.g

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

Output

I am an Animal

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

Example

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

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

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

Question: What self keyword does 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 The self represent the object of the class.

Question: 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 the inheritance in Pythons we pass the base class name in the parentheses of the drive class.

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

 

Question: What are dunders in python?
Answer: Dunders stands for double underscores, and these are the special magic methods used in python which has 2 underscores at the beginning and end of their name. Dunders are generally used for operator overloading in Python.

some e.g. of dunders methods are __init__, __str__, __del__,etc

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

Question: What open() and close() functions do 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 which needs to open and the mode of opening the file.

file_object = open(“filename”, mode)

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

The close() method is used to close the file object which is opened using open() method. It is very important to close the file once you are done working with it, the close() method close the file and terminate all the resources used by the file.

file_object.close()

Question: How python can be used for web development?
Answer: Python is well known for its web-framework. A web-framework is a tool which is used to create dynamic web application and python has many powerful web frameworks. Django and flask are the two most popular Python frameworks, and Django is the second most stared web-framework on the GitHub.

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

Question: What is Flask?

Answer: Flask is a Python micro web-framework and it uses jinja2 for web-templating.  As compared to Django, Flask has fewer libraries dependency which makes it a light weighted web-application.

Question: Give the major difference between Flask, Pyramid, and Django.

Answer:

Flask is a microframework, and it is generally used for small web-application. And it requires additional libraries to work with.

Pyramid is larger than Flask, that’s why it is used for big web-applications. It allows developers to work with different databases, templates, and URL structure.

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

Also Check: Click here for all Django interview questions

Question: Write a python program to save an image locally from the internet which URL is known.

Answer:

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

Question: 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 pip command

pip install virtualenv

Python command to create a virtual environment

python -m venv environment_name

Question: What does global keyword do in Python?

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

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

Question: What does nonlocal keyword do in Python?

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

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

Question: What are context managers in Python?

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

For example in general 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 exception prone and many times developers find it hard to code with this syntax. But in Python, we get context managers that provide an alternative way to write file handling code.

Example

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

Question: What is CPython?

Answer: CPython is the default implementation of Python Programming language, the Python we installed from the Python official website python.org is CPython. This is known as CPython because it is written in C Programming language.

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

Question: What is Monkey Patching In Python?

Answer: Monkey patching in python also known as Dynamic or runtime modification. According to the monkey-patching in Python, we can modify a class and its module during runtime.

Example

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

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


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

obj = monkey()
obj.func_method()

Output

function method

Python Coding Interview Questions

Often during the Python interviews, the company also organise the 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 questions could be anything, you might have to debug a Python code snippet or write a python program to solve a problem or implement some data structures using Python. Here are some of the most frequent Python coding interview questions.

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

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

Output

40

Question: What would be the output of this code 

print("5"*4)

Answer: 5555

Question: What would be the output of the following code

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

Answer:

1 
2 
[3, 4, 5]

Question: what would be the output?

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

Answer: 

[2, 4, 6]

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

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

Answer:

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

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

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

Answer:

True
False

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

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

Answer: None

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

print(bool(3<4)*20)

Answer:

20

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

lis=[1,2,3,4,5,6,7]
a=lis.sort()
b=sorted(lis)

if a==b:
  print(True)
else:
  print(False)

Answer:

False

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

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

func()

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

lis1,lis2=[1,2,3],[1,2,3]

if id(lis1)==id(lis2):
  print(True)
else:
  print(False)

Answer:

False

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

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

Answer:

[1, 2, 3]

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

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

Answer: 3

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

def re():

    return "Hello"

    print("Hello2")

print(re())

Answer:

Hello

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

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

Answer:
Yes

Question: What would be the output?

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

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

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

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

Question: Write a Python program to delete a file present in the same directory of the python script.

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

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

Question: 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=' ')

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

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

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

Answer:

Code:

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

Output:

Enter the String:daddad
daddad is a palindrome string

Conclusion

There are many job roles for a python developer. A python developer could be a web-developer, Data Analyst, Data Scientist, Machine learning, and Artificial Intelligent engineer. All the Python interview questions we have provided here cover mostly all the core python concepts with some advance 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 that Job interview questions. For instance, if you have a Django interview, we recommend you first read the Python interview questions and then read Django interview questions. This will help you to refresh your Python as well as Django skills.

If you like this article or have any suggestions regarding Python Interview Questions, please let us know by commenting down below.

People are also reading:

Leave a Reply

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