0% found this document useful (0 votes)
28 views105 pages

Interview Questions

Uploaded by

wlp74125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views105 pages

Interview Questions

Uploaded by

wlp74125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

1. What is Python?

What are the benefits of using Python

Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language,


it can be used to build almost any type of application with the right tools/libraries. Additionally, python
supports objects, modules, threads, exception-handling, and automatic memory management which help in
modelling real-world problems and building applications to solve these problems.

Benefits of using Python:

 Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes
readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of
scripting, is completely open-source, and supports third-party packages encouraging modularity and code
reuse.
 Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community
of developers for Rapid Application Development and deployment.

2. What is a dynamically typed language?

Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to
type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in
a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the
other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.

Type-checking can be done at two stages -

 Static - Data Types are checked before execution.


 Dynamic - Data Types are checked during execution.

Python is an interpreted language, executes each statement line by line and thus type-checking is done on the
fly, during execution. Hence, Python is a Dynamically Typed Language.

3. What is an Interpreted language?

An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and
Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly
from the source code, with no intermediary compilation step.

4. What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information
to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important
since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source
community requires you to follow these style guidelines sincerely and strictly.

5. What is Scope in Python?

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains
relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have
a scope defined for them where you could use their objects without any prefix. A few examples of scope created
during code execution in Python are as follows:
 A local scope refers to the local objects available in the current function.
 A global scope refers to the objects available throughout the code execution since their inception.
 A module-level scope refers to the global objects of the current module accessible in the program.
 An outermost scope refers to all the built-in names callable in the program. The objects in this scope are
searched last to find the name referenced.

Note: Local scope objects can be synced with global scope objects using keywords such as global.

6. What are lists and tuples? What is the key difference between the two?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects
stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6,
0.19], while tuples are represented with parantheses ('ansh', 5, 0.97).
But what is the real difference between the two? The key difference between the two is that while lists are
mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or
sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following
example on Python IDLE to confirm the difference:

my_tuple = ('sara', 6, 5, 0.97)


my_list = ['sara', 6, 5, 0.97]
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'sara'
my_tuple[0] = 'ansh' # modifying tuple => throws an error
my_list[0] = 'ansh' # modifying list => list modified
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'ansh'

7. What are the common built-in data types in Python?

There are several built-in data types in Python. Although, Python doesn't require data types to be defined
explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their
compatibility with each other are neglected. Python provides type() and isinstance() functions to check the
type of these variables. These data types can be grouped into the following categories-

 None Type:
None keyword represents the null values in Python. Boolean equality operation can be performed using these
NoneType objects.

Class Name Description


NoneType Represents the NULL values in Python.

 Numeric Types:
There are three distinct numeric types - integers, floating-point numbers, and complex numbers.
Additionally, booleans are a sub-type of integers.

Class Name Description


int Stores integer literals including hex, octal and binary numbers as integers
float Stores literals containing decimal values and/or exponent signs as floating-point numbers
complex Stores complex numbers in the form (A + Bj) and has attributes: real and imag
bool Stores boolean value (True or False).
Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point
numbers with user-defined precision.

 Sequence Types:
According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence
types have the in and not in operators defined for their traversing their elements. These operators share the
same priority as the comparison operations.

Class Name Description


list Mutable sequence used to store collection of items.
tuple Immutable sequence used to store collection of items.
range Represents an immutable sequence of numbers generated during execution.
str Immutable sequence of Unicode code points to store textual data.

Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str.

 Mapping Types:

A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and
there is currently only one standard mapping type, the dictionary.

Class Name Description


dict Stores comma-separated list of key: value pairs

 Set Types:
Currently, Python has two built-in set types - set and frozenset. set type is mutable and supports methods
like add() and remove(). frozenset type is immutable and can't be modified after creation.

Class Name Description


set Mutable unordered collection of distinct hashable objects.
frozenset Immutable collection of distinct hashable objects.

Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable
and thus, hashable, and can be used as a dictionary key or as an element of another set.

 Modules:
Module is an additional built-in type supported by the Python Interpreter. It supports one special operation,
i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a name defined in m's
symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct
assignment to this module is neither possible nor recommended.
 Callable Types:
Callable types are the types to which function call can be applied. They can be user-defined functions,
instance methods, generator functions, and some other built-in functions, methods and classes.
Refer to the documentation at docs.python.org for a detailed view of the callable types.

8. What is pass in Python?


The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty
blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the
following code, we may run into some errors during code execution.

def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block

9. What are modules and packages in Python?

Python packages and Python modules are two mechanisms that allow for modular programming in Python.
Modularizing has several advantages -

 Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand.
This makes development easier and less error-prone.
 Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If
they are written in a manner that reduces interdependency, it is less likely that modifications in a module might
impact other parts of the program.
 Reusability: Functions defined in a module can be easily reused by other parts of the application.
 Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from
other parts of the program.

Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or
variables defined and implemented. They can be imported and initialized once using the import statement. If
partial functionality is needed, import the requisite classes or functions using from foo import bar.

Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help
avoid clashes between global variable names, in a similar manner, packages help avoid clashes between
module names.
Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules
into a folder and there you have it, the folder name as the package name. Importing a module or its contents
from this package requires the package name as prefix to the module name joined by a dot.

Note: You can technically import the package as well, but alas, it doesn't import the modules within the package
to the local namespace, thus, it is practically useless.

10. What are global, protected and private attributes in Python?

 Global variables are public variables that are defined in the global scope. To use the variable in the global scope
inside a function, we use the global keyword.
 Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can
still be accessed and modified from outside the class they are defined in but a responsible developer should
refrain from doing so.
 Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be
accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

11. What is the use of self in Python?


Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods
of the class in python. It binds the attributes with the given arguments. self is used in different places and often
thought to be a keyword. But unlike in C++, self is not a keyword in Python.

12. What is __init__?

__init__ is a contructor method in Python and is automatically called to allocate memory when a new
object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing
methods and attributes of a class from local variables.

# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")

13. What is break, continue and pass in Python?

Break The break statement terminates the loop immediately and the control flows to the statement after
the body of the loop.
Continue The continue statement terminates the current iteration of the statement, skips the rest of the code
in the current iteration and the control flows to the next iteration of the loop.
Pass As explained above, the pass keyword in Python is generally used to fill up empty blocks and is
similar to an empty statement represented by a semi-colon in languages such as Java, C++,
Javascript, etc.
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
pass
if (p == 0):
current = p
break
elif (p % 2 == 0):
continue
print(p) # output => 1 3 1 3 1
print(current) # output => 0

14. What are unit tests in Python?

 Unit test is a unit testing framework of Python.


 Unit testing means testing different components of software separately. Can you think about why unit testing
is important? Imagine a scenario, you are building software that uses three components namely A, B, and C.
Now, suppose your software breaks at a point time. How will you find which component was responsible for
breaking the software? Maybe it was component A that failed, which in turn failed component B, and this
actually failed the software. There can be many such combinations.
 This is why it is necessary to test each and every component properly so that we know which component might
be highly responsible for the failure of the software.

15. What is docstring in Python?


 Documentation string or docstring is a multiline string used to document a specific code segment.
 The docstring should describe what the function or method does.

16. What is slicing in Python?

 As the name suggests, ‘slicing’ is taking parts of.


 Syntax for slicing is [start : stop : step]
 start is the starting index from where to slice a list or tuple
 stop is the ending index or where to sop.
 step is the number of steps to jump.
 Default value for start is 0, stop is number of items, step is 1.
 Slicing can be done on strings, arrays, lists, and tuples.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]

17. Explain how can you make a Python Script executable on Unix?

 Script file must begin with #!/usr/bin/env python

18. What is the difference between Python Arrays and lists?

 Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous.
It is a thin wrapper around C language arrays and consumes far less memory than lists.
 Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has
the disadvantage of consuming large memory.

import array
a = array.array('i', [1, 2, 3])
for i in a:
print(i, end=' ') #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str)
a = [1, 2, 'string']
for i in a:
print(i, end=' ') #OUTPUT: 1 2 string

Python Interview Questions for Experienced

19. How is memory managed in Python?

 Memory management in Python is handled by the Python Memory Manager. The memory allocated by the
manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and
being private, it is inaccessible to the programmer. Though, python does provide some core API functions to
work upon the private heap space.
 Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.
20. What are Python namespaces? Why are they used?

A namespace in Python ensures that object names in a program are unique and can be used without any conflict.
Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as
value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few
examples of namespaces are as follows:

 Local Namespace includes local names inside a function. the namespace is temporarily created for a function
call and gets cleared when the function returns.
 Global Namespace includes names from various imported packages/ modules that are being used in the
current project. This namespace is created when the package is imported in the script and lasts until the
execution of the script.
 Built-in Namespace includes built-in functions of core Python and built-in names for various types of
exceptions.

The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object
ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects
from an outer namespace.

21. What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope
resolution comes into play in Python automatically. A few examples of such behavior are:

 Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them
- log10(), acos(), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective
module, like math.exp() and cmath.exp().
 Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call.
However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws
a clear line between global and local variables, treating their namespaces as separate identities.

temp = 10 # global-scope variable


def func():
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 10

This behavior can be overridden using the global keyword inside the function, as shown in the following
example:

temp = 10 # global-scope variable


def func():
global temp
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 20

22. What are decorators in Python?

Decorators in Python are essentially functions that add functionality to an existing function in Python without
changing the structure of the function itself. They are represented the @decorator_name in Python and are
called in a bottom-up fashion. For example:

# decorator function to convert to lowercase


def lowercase_decorator(function):
def wrapper():
func = function()
string_lowercase = func.lower()
return string_lowercase
return wrapper
# decorator function to split words
def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
return 'Hello World'
hello() # output => [ 'hello' , 'world' ]

The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they
can even accept arguments for functions and can further modify those arguments before passing it to the
function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is
implemented to enforce encapsulation and thus, keep itself hidden from the global scope.

# decorator function to capitalize names


def names_decorator(function):
def wrapper(arg1, arg2):
arg1 = arg1.capitalize()
arg2 = arg2.capitalize()
string_hello = function(arg1, arg2)
return string_hello
return wrapper
@names_decorator
def say_hello(name1, name2):
return 'Hello ' + name1 + '! Hello ' + name2 + '!'
say_hello('sara', 'ansh') # output => 'Hello Sara! Hello Ansh!'

23. What are Dict and List comprehensions?

Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered
lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code
that might be considerably more verbose (containing more lines of code). Let's check out some examples,
where comprehensions can be truly beneficial:

 Performing mathematical operations on the entire list

my_list = [2, 3, 5, 7, 11]


squared_list = [x**2 for x in my_list] # list comprehension
# output => [4 , 9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list} # dict comprehension
# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

 Performing conditional filtering operations on the entire list

my_list = [2, 3, 5, 7, 11]


squared_list = [x**2 for x in my_list if x%2 != 0] # list comprehension
# output => [9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list if x%2 != 0} # dict comprehension
# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

 Combining multiple lists into one

Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one.

a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)] # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b] # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]

 Flattening a multi-dimensional list

A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work
upon its inner elements.

my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]
Note: List comprehensions have the same effect as the map method in other languages. They follow the
mathematical set builder notation rather than map and filter functions in Python.

24. What is lambda in Python? Why is it used?

Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a
single expression. It is generally used in situations requiring an anonymous function for a short time period.
Lambda functions can be used in either of the two ways:

 Assigning lambda functions to a variable:

mul = lambda a, b : a * b
print(mul(2, 5)) # output => 10

 Wrapping lambda functions inside another function:

def myWrapper(n):
return lambda a : a * n
mulFive = myWrapper(5)
print(mulFive(2)) # output => 10

25. How do you copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between
the existing object and the target variable name. To create copies of an object in Python, we need to use
the copy module. Moreover, there are two ways of creating copies for the given object using the copy module
-

Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the
original object. If either of the values is a reference to other objects, just the reference addresses for the same
are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects
referenced by the source object.

from copy import copy, deepcopy


list_1 = [1, 2, [3, 5], 4]
## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
list_2 # output => [1, 2, [3, 5, 6], 7]
list_1 # output => [1, 2, [3, 5, 6], 4]
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
list_3 # output => [1, 2, [3, 5, 6, 7], 8]
list_1 # output => [1, 2, [3, 5, 6], 4]

26. What is the difference between xrange and range in Python?


xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers,
with the only difference that range() returns a Python list, whereas, xrange() returns an xrange object.

So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static
list, it creates the value on the go. This technique is commonly used with an object-type generator and has
been termed as "yielding".

Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to
a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for
the generator (significantly less in comparison).

for i in xrange(10): # numbers from o to 9


print i # output => 0 1 2 3 4 5 6 7 8 9
for i in xrange(1,10): # numbers from 1 to 9
print i # output => 1 2 3 4 5 6 7 8 9
for i in xrange(1, 10, 2): # skip by two for next
print i # output => 1 3 5 7 9

Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same as what xrange used to
do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.

27. What is pickling and unpickling?

Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into
a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object. Here,
the pickle module comes into play.

Pickling:

 Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte
stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be
compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is
portable across versions.
 The function used for the above process is pickle.dump().

Unpickling:

 Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in
the file and loads the object to memory.
 The function used for the above process is pickle.load().

Note: Python has another, more primitive, serialization module called marshall, which exists primarily
to support .pyc files in Python and differs significantly from the pickle.
28. What are generators in Python?

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators,
in general, are used to create iterators with a different approach. They employ the use of yield keyword rather
than return to return a generator object.
Let's try and build a generator for fibonacci numbers -

## generate fibonacci numbers upto n


def fib(n):
p, q = 0, 1
while(p < n):
yield p
p, q = q, p + q
x = fib(10) # create generator object

## iterating using __next__(), for Python2, use next()


x.__next__() # output => 0
x.__next__() # output => 1
x.__next__() # output => 1
x.__next__() # output => 2
x.__next__() # output => 3
x.__next__() # output => 5
x.__next__() # output => 8
x.__next__() # error

## iterating using loop


for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8

29. What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can set to add additional directories where Python will
look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to
install in the global default location.

30. What is the use of help() and dir() functions?


help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If
no parameter is passed to the help() function, then an interactive help utility is launched on the console.
dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves
differently with different objects, as it aims to produce the most relevant data, rather than the complete
information.

 For Modules/Library objects, it returns a list of all attributes, contained in that module.
 For Class Objects, it returns a list of all valid attributes and base attributes.
 With no arguments passed, it returns a list of attributes in the current scope.

31. What is the difference between .py and .pyc files?

 .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We
get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It
is only created for the files that you import.
 Before executing a python program python interpreter checks for the compiled files. If the file is present, the
virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python
virtual machine executes it.
 Having .pyc file saves you the compilation time.

32. How Python is interpreted?

 Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the
implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.
 Source code is a file with .py extension.
 Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an
implementation of that virtual machine. This intermediate format is called “bytecode”.
 .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the
official CPython or JIT(Just in Time compiler) compiled by PyPy.

33. How are arguments passed by value or by reference in python?

 Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change
the value of the original object.
 Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change
the value of the original object.

In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
print(arr) #Output: => [1, 2, 3]
appendNumber(arr)
print(arr) #Output: => [1, 2, 3, 4]

34. What are iterators in Python?

 An iterator is an object.
 It remembers its state i.e., where it is during iteration (see code below to see how)
 __iter__() method initializes an iterator.
 It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching
the end of iterable object __next__() must return StopIteration exception.
 It is also self-iterable.
 Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.

class ArrayList:
def __init__(self, number_list):
self.numbers = number_list
def __iter__(self):
self.pos = 0
return self
def __next__(self):
if(self.pos < len(self.numbers)):
self.pos += 1
return self.numbers[self.pos - 1]
else:
raise StopIteration
array_obj = ArrayList([1, 2, 3])
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration

35. Explain how to delete a file in Python?

Use command os.remove(file_name)

import os
os.remove("ChangedFile.csv")
print("File Removed!")

36. Explain split() and join() functions in Python?

 You can use split() function to split a string based on a delimiter to a list of strings.
 You can use join() function to join a list of strings based on a delimiter to give a single string.

string = "This is a string."


string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
print(string_list) #output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list)) #output: This is a string.

37. What does *args and **kwargs mean?

*args

 *args is a special syntax used in the function definition to pass variable-length arguments.
 “*” means variable length and “args” is the name used by convention. You can use any other.
def multiply(a, b, *argv):
mul = a * b
for num in argv:
mul *= num
return mul
print(multiply(1, 2, 3, 4, 5)) #output: 120

**kwargs

 **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
 Here, also, “kwargs” is used just by convention. You can use any other name.
 Keyworded argument means a variable that has a name when passed to a function.
 It is actually a dictionary of the variable names and its value.

def tellArguments(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

38. What are negative indexes and why are they used?

 Negative indexes are the indexes from the end of the list or tuple or string.
 Arr[-1] means the last element of array Arr[]

arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5

Python OOPS Interview Questions

39. How do you create a class in Python?

To create a class in python, we use the keyword “class” as shown in the example below:

class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name

To instantiate or create an object from the class created above, we do the following:

emp_1=InterviewbitEmployee("Mr. Employee")

To access the name attribute, we just call the attribute using the dot operator as shown below:

print(emp_1.emp_name)
# Prints Mr. Employee
To create methods inside the class, we include the methods under the scope of the class as shown below:

class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name

def introduce(self):
print("Hello I am " + self.emp_name)

The self parameter in the init and introduce functions represent the reference to the current class instance
which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter
of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown
below:

emp_1.introduce()

The overall program would look like this:

class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name

def introduce(self):
print("Hello I am " + self.emp_name)

# create an object of InterviewbitEmployee class


emp_1 = InterviewbitEmployee("Mr Employee")
print(emp_1.emp_name) #print employee name
emp_1.introduce() #introduce the employee

40. How does inheritance work in python? Explain it with an example.

Inheritance gives the power to a class to access all attributes and methods of another class. It aids in code
reusability and helps the developer to maintain applications without redundant code. The class inheriting from
another class is a child class or also called a derived class. The class from which a child class derives the
members are called parent class or superclass.

Python supports different kinds of inheritance, they are:

 Single Inheritance: Child class derives members of one parent class.

# Parent class
class ParentClass:
def par_func(self):
print("I am parent class function")

# Child class
class ChildClass(ParentClass):
def child_func(self):
print("I am child class function")

# Driver code
obj1 = ChildClass()
obj1.par_func()
obj1.child_func()

 Multi-level Inheritance: The members of the parent class, A, are inherited by child class which is then
inherited by another child class, B. The features of the base class and the derived class are further inherited
into the new derived class, C. Here, A is the grandfather class of class C.

# Parent class
class A:
def __init__(self, a_name):
self.a_name = a_name

# Intermediate class
class B(A):
def __init__(self, b_name, a_name):
self.b_name = b_name
# invoke constructor of class A
A.__init__(self, a_name)

# Child class
class C(B):
def __init__(self,c_name, b_name, a_name):
self.c_name = c_name
# invoke constructor of class B
B.__init__(self, b_name, a_name)

def display_names(self):
print("A name : ", self.a_name)
print("B name : ", self.b_name)
print("C name : ", self.c_name)

# Driver code
obj1 = C('child', 'intermediate', 'parent')
print(obj1.a_name)
obj1.display_names()

 Multiple Inheritance: This is achieved when one child class derives members from more than one parent
class. All features of parent classes are inherited in the child class.

# Parent class1
class Parent1:
def parent1_func(self):
print("Hi I am first Parent")

# Parent class2
class Parent2:
def parent2_func(self):
print("Hi I am second Parent")

# Child class
class Child(Parent1, Parent2):
def child_func(self):
self.parent1_func()
self.parent2_func()

# Driver's code
obj1 = Child()
obj1.child_func()

 Hierarchical Inheritance: When a parent class is derived by more than one child class, it is called hierarchical
inheritance.

# Base class
class A:
def a_func(self):
print("I am from the parent class.")

# 1st Derived class


class B(A):
def b_func(self):
print("I am from the first child.")

# 2nd Derived class


class C(A):
def c_func(self):
print("I am from the second child.")

# Driver's code
obj1 = B()
obj2 = C()
obj1.a_func()
obj1.b_func() #child 1 method
obj2.a_func()
obj2.c_func() #child 2 method

41. How do you access parent members in the child class?

Following are the ways using which you can access parent class members within a child class:

 By using Parent class name: You can use the name of the parent class to access the attributes as shown in the
example below:

class Parent(object):
# Constructor
def __init__(self, name):
self.name = name

class Child(Parent):
# Constructor
def __init__(self, name, age):
Parent.name = name
self.age = age

def display(self):
print(Parent.name, self.age)

# Driver Code
obj = Child("Interviewbit", 6)
obj.display()

 By using super(): The parent class members can be accessed in child class using the super keyword.

class Parent(object):
# Constructor
def __init__(self, name):
self.name = name
class Child(Parent):
# Constructor
def __init__(self, name, age):
'''
In Python 3.x, we can also use super().__init__(name)
'''
super(Child, self).__init__(name)
self.age = age

def display(self):
# Note that Parent.name cant be used
# here since super() is used in the constructor
print(self.name, self.age)

# Driver Code
obj = Child("Interviewbit", 6)
obj.display()

42. Are access specifiers used in python?

Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does
not derive this from any variables. It has the concept of imitating the behaviour of variables by making use of a
single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables
without prefixed underscores are public.

Example:

# to demonstrate access specifiers


class InterviewbitEmployee:

# protected members
_emp_name = None
_age = None

# private members
__branch = None

# constructor
def __init__(self, emp_name, age, branch):
self._emp_name = emp_name
self._age = age
self.__branch = branch

#public member
def display():
print(self._emp_name +" "+self._age+" "+self.__branch)

43. Is it possible to call parent class without its instance creation?

Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method.

44. How is an empty class created in python?


An empty class does not have any members defined in it. It is created by using the pass keyword (the pass
command does nothing in python). We can create objects for this class outside the class.
For example-

class EmptyClassDemo:
pass
obj=EmptyClassDemo()
obj.name="Interviewbit"
print("Name created= ",obj.name)

Output:
Name created = Interviewbit

45. Differentiate between new and override modifiers.

The new modifier is used to instruct the compiler to use the new implementation and not the base class
function. The Override modifier is useful for overriding a base class function inside the child class.

46. Why is finalize used?

Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection
method is invoked. This helps in performing memory management tasks.

47. What is init method in python?

The init method works similarly to the constructors in Java. The method is run as soon as an object is
instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of
instantiation.
For example:

class InterviewbitEmployee:

# init method / constructor


def __init__(self, emp_name):
self.emp_name = emp_name

# introduce method
def introduce(self):
print('Hello, I am ', self.emp_name)

emp = InterviewbitEmployee('Mr Employee') # __init__ method is called here and initializes the object name
with "Mr Employee"
emp.introduce()

48. How will you check if a class is a child of another class?

This is done by using a method called issubclass() provided by python. The method tells us if any class is a
child of another class by returning true or false accordingly.
For example:

class Parent(object):
pass
class Child(Parent):
pass

# Driver Code
print(issubclass(Child, Parent)) #True
print(issubclass(Parent, Child)) #False

 We can check if an object is an instance of a class by making use of isinstance() method:

obj1 = Child()
obj2 = Parent()
print(isinstance(obj2, Child)) #False
print(isinstance(obj2, Parent)) #True

Python Pandas Interview Questions

49. What do you know about pandas?

 Pandas is an open-source, python-based library used in data manipulation applications requiring high
performance. The name is derived from “Panel Data” having multidimensional data. This was developed in
2008 by Wes McKinney and was developed for data analysis.
 Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it,
model it, and analyze the data.

50. Define pandas dataframe.

A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns.
The syntax for creating dataframe:

import pandas as pd
dataframe = pd.DataFrame( data, index, columns, dtype)

where:

 data - Represents various forms like series, map, ndarray, lists, dict etc.
 index - Optional argument that represents an index to row labels.
 columns - Optional argument for column labels.
 Dtype - the data type of each column. Again optional.

51. How will you combine different pandas dataframes?

The dataframes can be combines using the below approaches:

 append() method: This is used to stack the dataframes horizontally. Syntax:

df1.append(df2)

 concat() method: This is used to stack dataframes vertically. This is best used when the dataframes have the
same columns and similar fields. Syntax:
pd.concat([df1, df2])

 join() method: This is used for extracting data from various dataframes having one or more common columns.

df1.join(df2)

52. Can you create a series from the dictionary object in pandas?

One dimensional array capable of storing different data types is called a series. We can create pandas series
from a dictionary object as shown below:

import pandas as pd
dict_info = {'key1' : 2.0, 'key2' : 3.1, 'key3' : 2.2}
series_obj = pd.Series(dict_info)
print (series_obj)
Output:
x 2.0
y 3.1
z 2.2
dtype: float64

If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order
for constructing the index. In case the index is passed, then values of the index label will be extracted from the
dictionary.

53. How will you identify and deal with missing values in a dataframe?

We can identify if a dataframe has missing values by using the isnull() and isna() methods.

missing_data_count=df.isnull().sum()

We can handle missing values by either replacing the values in the column with 0 as follows:

df[‘column_name’].fillna(0)

Or by replacing it with the mean value of the column

df[‘column_name’] = df[‘column_name’].fillna((df[‘column_name’].mean()))

54. What do you understand by reindexing in pandas?

Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are
missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new
index is produced that is equivalent to the current one. The copy value is set to False. This is also used for
changing the index of rows and columns in the dataframe.

55. How to add new column to pandas dataframe?

A new column can be added to a pandas dataframe as follows:

import pandas as pd
data_info = {'first' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'second' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_info)
#To add new column third
df['third']=pd.Series([10,20,30],index=['a','b','c'])
print (df)
#To add new column fourth
df['fourth']=df['first']+info['third']
print (df)

56. How will you delete indices, rows and columns from a dataframe?

To delete an Index:

 Execute del df.index.name for removing the index by name.


 Alternatively, the df.index.name can be assigned to None.
 For example, if you have the below dataframe:

Column 1
Names
John 1
Jack 2
Judy 3
Jim 4

 To drop the index name “Names”:

df.index.name = None
# Or run the below:
# del df.index.name
print(df)
Column 1
John 1
Jack 2
Judy 3
Jim 4

To delete row/column from dataframe:

 drop() method is used to delete row/column from dataframe.


 The axis argument is passed to the drop method where if the value is 0, it indicates to drop/delete a row and if
1 it has to drop the column.
 Additionally, we can try to delete the rows/columns in place by setting the value of inplace to True. This makes
sure that the job is done without the need for reassignment.
 The duplicate values from the row/column can be deleted by using the drop_duplicates() method.
57. Can you get items of series A that are not available in another series B?

This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below.

import pandas as pd
df1 = pd.Series([2, 4, 8, 10, 12])
df2 = pd.Series([8, 12, 10, 15, 16])
df1=df1[~df1.isin(df2)]
print(df1)
"""
Output:
0 2
1 4
dtype: int64
"""

58. How will you get the items that are not common to both the given series A and B?

We can achieve this by first performing the union of both series, then taking the intersection of both series.
Then we follow the approach of getting items of union that are not there in the list of the intersection.

The following code demonstrates this:

import pandas as pd
import numpy as np
df1 = pd.Series([2, 4, 5, 8, 10])
df2 = pd.Series([8, 10, 13, 15, 17])
p_union = pd.Series(np.union1d(df1, df2)) # union of series
p_intersect = pd.Series(np.intersect1d(df1, df2)) # intersection of series
unique_elements = p_union[~p_union.isin(p_intersect)]
print(unique_elements)
"""
Output:
0 2
1 4
2 5
5 13
6 15
7 17
dtype: int64
"""

59. While importing data from different sources, can the pandas library recognize dates?

Yes, they can, but with some bit of help. We need to add the parse_dates argument while we are reading data
from the sources. Consider an example where we read data from a CSV file, we may encounter different date-
time formats that are not readable by the pandas library. In this case, pandas provide flexibility to build our
custom date parser with the help of lambda functions as shown below:

import pandas as pd
from datetime import datetime
dateparser = lambda date_val: datetime.strptime(date_val, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv("some_file.csv", parse_dates=['datetime_column'], date_parser=dateparser)

Numpy Interview Questions

60. What do you understand by NumPy?

NumPy is one of the most popular, easy-to-use, versatile, open-source, python-based, general-purpose package
that is used for processing arrays. NumPy is short for NUMerical PYthon. This is very famous for its highly
optimized tools that result in high performance and powerful N-Dimensional array processing feature that is
designed explicitly to work on complex arrays. Due to its popularity and powerful performance and its
flexibility to perform various operations like trigonometric operations, algebraic and statistical computations,
it is most commonly used in performing scientific computations and various broadcasting functions. The
following image shows the applications of NumPy:

61. How are NumPy arrays advantageous over python lists?


 The list data structure of python is very highly efficient and is capable of performing various functions. But,
they have severe limitations when it comes to the computation of vectorized operations which deals with
element-wise multiplication and addition. The python lists also require the information regarding the type of
every element which results in overhead as type dispatching code gets executes every time any operation is
performed on any element. This is where the NumPy arrays come into the picture as all the limitations of
python lists are handled in NumPy arrays.
 Additionally, as the size of the NumPy arrays increases, NumPy becomes around 30x times faster than the
Python List. This is because the Numpy arrays are densely packed in the memory due to their homogenous
nature. This ensures the memory free up is also faster.

62. What are the steps to create 1D, 2D and 3D arrays?

 1D array creation:

import numpy as np
one_dimensional_list = [1,2,4]
one_dimensional_arr = np.array(one_dimensional_list)
print("1D array is : ",one_dimensional_arr)

 2D array creation:

import numpy as np
two_dimensional_list=[[1,2,3],[4,5,6]]
two_dimensional_arr = np.array(two_dimensional_list)
print("2D array is : ",two_dimensional_arr)

 3D array creation:

import numpy as np
three_dimensional_list=[[[1,2,3],[4,5,6],[7,8,9]]]
three_dimensional_arr = np.array(three_dimensional_list)
print("3D array is : ",three_dimensional_arr)

 ND array creation: This can be achieved by giving the ndmin attribute. The below example demonstrates the
creation of a 6D array:

import numpy as np
ndArray = np.array([1, 2, 3, 4], ndmin=6)
print(ndArray)
print('Dimensions of array:', ndArray.ndim)

63. You are given a numpy array and a new column as inputs. How will you delete the second column
and replace the column with a new column value?

Example:
Given array:

[[35 53 63]
[72 12 22]
[43 84 56]]

New Column values:


[
20
30
40
]

Solution:

import numpy as np
#inputs
inputArray = np.array([[35,53,63],[72,12,22],[43,84,56]])
new_col = np.array([[20,30,40]])
# delete 2nd column
arr = np.delete(inputArray , 1, axis = 1)
#insert new_col to array
arr = np.insert(arr , 1, new_col, axis = 1)
print (arr)

64. How will you efficiently load data from a text file?

We can use the method numpy.loadtxt() which can automatically read the file’s header and footer lines and the
comments if any.

This method is highly efficient and even if this method feels less efficient, then the data should be represented
in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of
NumPy used.

Following are the file formats that are supported:

 Text files: These files are generally very slow, huge but portable and are human-readable.
 Raw binary: This file does not have any metadata and is not portable. But they are fast.
 Pickle: These are borderline slow and portable but depends on the NumPy versions.
 HDF5: This is known as the High-Powered Kitchen Sink format which supports both PyTables and h5py format.
 .npy: This is NumPy's native binary data format which is extremely simple, efficient and portable.

65. How will you read CSV data into an array in NumPy?

This can be achieved by using the genfromtxt() method by setting the delimiter as a comma.

from numpy import genfromtxt


csv_data = genfromtxt('sample_file.csv', delimiter=',')

66. How will you sort the array based on the Nth column?

For example, consider an array arr.

arr = np.array([[8, 3, 2],


[3, 6, 5],
[6, 1, 4]])

Let us try to sort the rows by the 2nd column so that we get:
[[6, 1, 4],
[8, 3, 2],
[3, 6, 5]]

We can do this by using the sort() method in numpy as:

import numpy as np
arr = np.array([[8, 3, 2],
[3, 6, 5],
[6, 1, 4]])
#sort the array using np.sort
arr = np.sort(arr.view('i8,i8,i8'),
order=['f1'],
axis=0).view(np.int)

We can also perform sorting and that too inplace sorting by doing:

arr.view('i8,i8,i8').sort(order=['f1'], axis=0)

67. How will you find the nearest value in a given numpy array?

We can use the argmin() method of numpy as shown below:

import numpy as np
def find_nearest_value(arr, value):
arr = np.asarray(arr)
idx = (np.abs(arr - value)).argmin()
return arr[idx]
#Driver code
arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742])
value = 0.52
print(find_nearest_value(arr, value)) # Prints 0.5645

68. How will you reverse the numpy array using one line of code?

This can be done as shown in the following:

reversed_array = arr[::-1]

where arr = original given array, reverse_array is the resultant after reversing all elements in the input.

69. How will you find the shape of any given NumPy array?

We can use the shape attribute of the numpy array to find the shape. It returns the shape of the array in terms
of row count and column count of the array.

import numpy as np
arr_two_dim = np.array([("x1","x2", "x3","x4"),
("x5","x6", "x7","x8" )])
arr_one_dim = np.array([3,2,4,5,6])
# find and print shape
print("2-D Array Shape: ", arr_two_dim.shape)
print("1-D Array Shape: ", arr_one_dim.shape)
"""
Output:
2-D Array Shape: (2, 4)
1-D Array Shape: (5,)
"""

Python Libraries Interview Questions

70. Differentiate between a package and a module in python.

The module is a single python file. A module can import other modules (other python files) as objects. Whereas,
a package is the folder/directory where different sub-packages and the modules reside.

A python module is created by saving a file with the extension of .py. This file will have classes and functions
that are reusable in the code as well as across modules.

A python package is created by following the below steps:

 Create a directory and give a valid name that represents its operation.
 Place modules of one kind in this directory.
 Create __init__.py file in this directory. This lets python know the directory we created is a package. The
contents of this package can be imported across different modules in other packages to reuse the functionality.

71. What are some of the most commonly used built-in modules in Python?

Python modules are the files having python code which can be functions, variables or classes. These go by .py
extension. The most commonly available built-in modules are:

 os
 math
 sys
 random
 re
 datetime
 JSON

72. What are lambda functions?

Lambda functions are generally inline, anonymous functions represented by a single expression. They are used
for creating function objects during runtime. They can accept any number of parameters. They are usually used
where functions are required only for a short period. They can be used as:

mul_func = lambda x,y : x*y


print(mul_func(6, 4))
# Output: 24

73. How can you generate random numbers?

Python provides a module called random using which we can generate random numbers.
 We have to import a random module and call the random() method as shown below:
o The random() method generates float values lying between 0 and 1 randomly.

import random
print(random.random())

 To generate customised random numbers between specified ranges, we can use the randrange() method
Syntax: randrange(beginning, end, step)
For example:

import random
print(random.randrange(5,100,2))

74. Can you easily check if all characters in the given string is alphanumeric?

This can be easily done by making use of the isalnum() method that returns true in case the string has only
alphanumeric characters.

For Example -

"abdc1321".isalnum() #Output: True


"xyz@123$".isalnum() #Output: False

Another way is to use match() method from the re (regex) module as shown:

import re
print(bool(re.match('[A-Za-z0-9]+$','abdc1321'))) # Output: True
print(bool(re.match('[A-Za-z0-9]+$','xyz@123$'))) # Output: False

75. What are the differences between pickling and unpickling?

Pickling is the conversion of python objects to binary form. Whereas, unpickling is the conversion of binary
form data to python objects. The pickled objects are used for storing in disks or external memory locations.
Unpickled objects are used for getting the data back as python objects upon which processing can be done in
python.

Python provides a pickle module for achieving this. Pickling uses the pickle.dump() method to dump python
objects into disks. Unpickling uses the pickle.load() method to get back the data as python objects.

76. Define GIL.

GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in
effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel
computing). The following diagram represents how GIL works.
Based on the above diagram, there are three threads. First Thread acquires the GIL first and starts the I/O
execution. When the I/O operations are done, thread 1 releases the acquired GIL which is then taken up by the
second thread. The process repeats and the GIL are used by different threads alternatively until the threads
have completed their execution. The threads not having the GIL lock goes into the waiting state and resumes
execution only when it acquires the lock.

77. Define PYTHONPATH.

It is an environment variable used for incorporating additional directories during the import of a module or a
package. PYTHONPATH is used for checking if the imported packages or modules are available in the existing
directories. Not just that, the interpreter uses this environment variable to identify which module needs to be
loaded.

78. Define PIP.

PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules.
It is a command-line tool providing a seamless interface for installing different python modules. It searches
over the internet for the package and installs them into the working directory without the need for any
interaction with the user. The syntax for this is:

pip install <package_name>

79. Are there any tools for identifying bugs and performing static analysis in python?

Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively.
PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity.
Pylint checks for the module’s coding standards and supports different plugins to enable custom features to
meet this requirement.

80. Differentiate between deep and shallow copies.

 Shallow copy does the task of creating new objects storing references of original elements. This does not
undergo recursion to create copies of nested objects. It just copies the reference details of nested objects.
 Deep copy creates an independent and new copy of an object and even copies all the nested objects of the
original element recursively.

81. What is main function in python? How do you invoke it?

In the world of programming languages, the main is considered as an entry point of execution for a program.
But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python
does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of
main. This can be done by defining user-defined main() function and by using the __name__ property of python
file. This __name__ variable is a special built-in variable that points to the name of the current module. This can
be done as shown below:

def main():
print("Hi Interviewbit!")
if __name__=="__main__":
main()

Python Programming Examples

82. Write python function which takes a variable number of arguments.

A function that takes variable arguments is called a function prototype. Syntax:

def function_name(*arg_list)

For example:

def func(*var):
for i in var:
print(i)
func(1)
func(20,1,6)

The * in the function argument represents variable arguments in the function.

83. WAP (Write a program) which takes a sequence of numbers and check if all numbers are unique.

You can do this by converting the list to set by using set() method and comparing the length of this set with the
length of the original list. If found equal, return True.

def check_distinct(data_list):
if len(data_list) == len(set(data_list)):
return True
else:
return False;
print(check_distinct([1,6,5,8])) #Prints True
print(check_distinct([2,2,5,5,7,8])) #Prints False

84. Write a program for counting the number of every character of a given text file.

The idea is to use collections and pprint module as shown below:

import collections
import pprint
with open("sample_file.txt", 'r') as data:
count_data = collections.Counter(data.read().upper())
count_value = pprint.pformat(count_data)
print(count_value)

85. Write a program to check and return the pairs of a given array A whose sum value is equal to a target
value N.
This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current
value of the array, x. If the map has the value of (N-x), then there is our pair.

def print_pairs(arr, N):


# hash set
hash_set = set()

for i in range(0, len(arr)):


val = N-arr[i]
if (val in hash_set): #check if N-x is there in set, print the pair
print("Pairs " + str(arr[i]) + ", " + str(val))
hash_set.add(arr[i])

# driver code
arr = [1, 2, 40, 3, 9, 4]
N=3
print_pairs(arr, N)

86. Write a Program to add two integers >0 without using the plus operator.

We can use bitwise operators to achieve this.

def add_nums(num1, num2):


while num2 != 0:
data = num1 & num2
num1 = num1 ^ num2
num2 = data << 1
return num1
print(add_nums(2, 10))

87. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants:

ax + by = c
mx + ny = o

By solving the equation, we get:

a, b, c, m, n, o = 5, 9, 4, 7, 9, 4
temp = a*n - b*m
if n != 0:
x = (c*n - b*o) / temp
y = (a*o - m*c) / temp
print(str(x), str(y))

88. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.

We can use the re module of python to perform regex pattern comparison here.

import re
def match_text(txt_data):
pattern = 'ab{4,8}'
if re.search(pattern, txt_data): #search for pattern in txt_data
return 'Match found'
else:
return('Match not found')
print(match_text("abc")) #prints Match not found
print(match_text("aabbbbbc")) #prints Match found

89. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.

We can again use the re module to convert the date string as shown below:

import re
def transform_date_format(date):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date)
date_input = "2021-08-01"
print(transform_date_format(date_input))

You can also use the datetime module as shown below:

from datetime import datetime


new_date = datetime.strptime("2021-08-01", "%Y-%m-%d").strftime("%d:%m:%Y")
print(new_data)

90. Write a Program to combine two different dictionaries. While combining, if you find the same keys,
you can add the values of these same keys. Output the new dictionary

We can use the Counter method from the collections module

from collections import Counter


d1 = {'key1': 50, 'key2': 100, 'key3':200}
d2 = {'key1': 200, 'key2': 100, 'key4':300}
new_dict = Counter(d1) + Counter(d2)
print(new_dict)

91. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google
Drive?

We can use the StringIO module from the io module to read from the Google Drive link and then we can use the
pandas library using the obtained data source.

from io import StringIO


import pandas
csv_link = "https://docs.google.com/spreadsheets/d/..."
data_source = StringIO.StringIO(requests.get(csv_link).content))
dataframe = pd.read_csv(data_source)
print(dataframe.head())

Conclusion:

In this article, we have seen commonly asked interview questions for a python developer. These questions
along with regular problem practice sessions will help you crack any python based interviews. Over the years,
python has gained a lot of popularity amongst the developer’s community due to its simplicity and ability to
support powerful computations. Due to this, the demand for good python developers is ever-growing.
Nevertheless, to mention, the perks of being a python developer are really good. Along with theoretical
knowledge in python, there is an emphasis on the ability to write good quality code as well. So, keep learning
and keep practicing problems and without a doubt, you can crack any interviews.

Python MCQ

1. Suppose list1 = [3,4,5,2,1,0], what is list1 after list1.pop(1)?


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

2.What is the output of the following statement "Hello World"[::-1]?

"Hello World"
"World Hello"
"dlroW olleH"
"olleH dlroW"

3.What is the difference between lists and tuples?


List is a sequence data type, while tuple is not.
Tuples are mutable but lists are immutable.
Tuple is a sequence data type, while lists is not.
Lists are mutable but tuples are immutable.

4. Let func = lambda a, b : (a ** b), what is the output of func(float(10),20) ?


100000000000000000000
1e+20
100000000000000000000.0
1.0e+20

5. Which statement is false for __init__?


__init__ is called manually on object creation.
__init__ is a constructor method in Python.
All classes have a __init__ method associated with them.
__init__ allocates memory for objects.

6. Which of the following is the function responsible for pickling?


pickle.save()
pickle.store()
pickle.pickle()
pickle.dump()

7. Which of the following is a protected attribute?


__sara__
__ansh
_sara_
ansh__

8. Which of the following is untrue for Python namespaces?


Python namespaces are implemented as a dictionary in Python.
Python namespaces have keys as addresses of the objects.
Lifecycle of a namespace depends upon the scope of the objects they are mapped to.
Namespaces ensure that object names in a program are unique.
9. Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'], what is the output of ["".join([i, j]) for i, j in zip(list1, list2)]?
['s', 'a', 'r', 'a', 'a', 'n', 's', 'h']
['s', 'r', 'a', 's', 'a', 'a', 'n', 'h']
['sa', 'ra', 'an', 'sh']
['sa', 'sa', 'sn', 'sh', 'ra', 'ra', 'rn', 'rh', 'aa', 'aa', 'an', 'ah', 'sa', 'sa', 'sn', 'sh']

10.time.time() in Python returns?


Current time.
Current time in milliseconds.
Current time in milliseconds since midnight, January 1, 1970.
Current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time).

11.What is the output of the following program?


class A(object):
def __init__(self, a):
self.num = a
def mul_two(self):
self.num *= 2

class B(A):
def __init__(self, a):
X.__init__(self, a)
def mul_three(self):
self.num *= 3

obj = B(4)
print(obj.num)
obj.mul_two()
print(obj.num)

obj.mul_three()
print(obj.num)
4 8 24
4 4 64
4 8 64
None of the above

12.What is the output of the below program?


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

def getHumanName(self):
return self.human_name

def isEmployee(self):
return False

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

def isEmployee(self):
return True

def get_emp_id(self):
return self.emp_id

# Driver code
employee = IBEmployee("Mr Employee", "IB007")
print(employee.getHumanName(), employee.isEmployee(), employee.get_emp_id()
(None, True, ‘IB007’)
(‘Mr Employee’, True, ‘IB007’)
(“”, False, ‘IB007’)
Runtime error

13. Which among the below options will correct the below error obtained while reading “sample_file.csv” in
pandas?
Traceback (most recent call last): File "<input>", line 10, in<module> UnicodeEncodeError:
'ascii' codec can't encode character.
pd.read_csv(“sample_file.csv”, encoding=‘utf-8’)
pd.read_csv(“sample_file.csv”, compression=‘gzip’)
pd.read_csv(“sample_file.csv”, dialect=‘comma’)
None of the above

14.Which among the following options helps us to check whether a pandas dataframe is empty?
df.emptyframe
df.blank
df.isempty
df.empty

15.How will you find the location of numbers which are multiples of 5 in a series?
import pandas as pd
import numpy as np
series_data = pd.Series(np.random.randint(1, 20, 7))
#insert code here
np.search(series_data % 5)
np.find(series_data % 5 ==0)
np.argwhere(series_data % 5==0)
np.locate(series_data % 5)

16.What is the output of the below code?


class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name

first_name = "XYZ"
person = Person(first_name, "ABC")
first_name = "LMN"
person.last_name = "PQR"
print(person.first_name, person.last_name)
XYZ ABC
XYZ PQR
LMN ABC
LMN PQR

17.Which among the below options picks out negative numbers from the given list.
[num for num<0 in list]
[num<0 in list]
[num for num in list if num<0]
[num in list for num<0]

18.What is the output of the below code?


main_dict={}
def insert_item(item):
if item in main_dict:
main_dict[item] += 1
else:
main_dict[item] = 1
#Driver code
insert_item('Key1')
insert_item('Key2')
insert_item('Key2')
insert_item('Key3')
insert_item('Key1')
print (len(main_dict))
5
Runtime error
Duplicate Key Exception
3

19.What is the output of the below code?


class X:
def __init__(self):
self.__num1 = 5
self.num2 = 2

def display_values(self):
print(self.__num1, self.num2)
class Y(X):
def __init__(self):
super().__init__()
self.__num1 = 1
self.num2 = 6
obj = Y()
obj.display_values()
56
12
52
16

ython Interview Questions

A list of frequently asked Python interview questions with answers for freshers and experienced are given
below.
1) What is Python?

Python was created by Guido van Rossum, and released in 1991.

It is a general-purpose computer programming language. It is a high-level, object-oriented language which can


run equally on different platforms such as Windows, Linux, UNIX, and Macintosh. Its high-level built-in data
structures, combined with dynamic typing and dynamic binding. It is widely used in data science, machine
learning and artificial intelligence domain.

It is easy to learn and require less code to develop the applications.

39.5M

696

Prime Ministers of India | List of Prime Minister of India (1947-2020)

It is widely used for:

o Web development (server-side).

o Software development.

o Mathematics.

o System scripting.
2) Why Python?

o Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.

o Python is compatible with different platforms like Windows, Mac, Linux, Raspberry Pi, etc.

o Python has a simple syntax as compared to other languages.

o Python allows a developer to write programs with fewer lines than some other programming
languages.

o Python runs on an interpreter system, means that the code can be executed as soon as it is written. It
helps to provide a prototype very quickly.

o Python can be described as a procedural way, an object-orientated way or a functional way.

o The Python interpreter and the extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.

3) What are the applications of Python?

Python is used in various software domains some application areas are given below.

o Web and Internet Development

o Games

o Scientific and computational applications

o Language development

o Image processing and graphic design applications

o Enterprise and business applications development

o Operating systems

o GUI based desktop applications


Python provides various web frameworks to develop web applications. The popular python web frameworks
are Django, Pyramid, Flask.

Python's standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.

Python's SciPy and NumPy helps in scientific and computational application development.

Python's Tkinter library supports to create a desktop based GUI applications.

4) What are the advantages of Python?

Advantages of Python are:

o Python is Interpreted language

Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes
instructions directly.
o It is Free and open source

Free and open source: It is an open-source project which is publicly available to reuse. It can be downloaded
free of cost.

o It is Extensible

Extensible: It is very flexible and extensible with any module.

o Object-oriented

Object-oriented: Python allows to implement the Object-Oriented concepts to build application solution.

o It has Built-in data structure

Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the
language.

o Readability

o High-Level Language

o Cross-platform

Portable: Python programs can run on cross platforms without affecting its performance.

5) What is PEP 8?
PEP 8 stands for Python Enhancement Proposal, it can be defined as a document that helps us to provide the
guidelines on how to write the Python code. It is basically a set of rules that specify how to format Python code
for maximum readability. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.

6) What do you mean by Python literals?

Literals can be defined as a data which is given in a variable or constant. Python supports the following literals:

String Literals

String literals are formed by enclosing text in the single or double quotes. For example, string literals are string
values.

Example:

1. # in single quotes
2. single = 'JavaTpoint'
3. # in double quotes
4. double = "JavaTpoint"
5. # multi-line String
6. multi = '''''Java
7. T
8. point'''
9.
10. print(single)
11. print(double)
12. print(multi)

Output:

JavaTpoint
JavaTpoint
Java
T
point

Numeric Literals

Python supports three types of numeric literals integer, float and complex.

Example:
1. # Integer literal
2. a = 10
3. #Float Literal
4. b = 12.3
5. #Complex Literal
6. x = 3.14j
7. print(a)
8. print(b)
9. print(x)

Output:

10
12.3
3.14j

Boolean Literals

Boolean literals are used to denote Boolean values. It contains either True or False.

Example:

1. p = (1 == True)
2. q = (1 == False)
3. r = True + 3
4. s = False + 7
5.
6. print("p is", p)
7. print("q is", q)
8. print("r:", r)
9. print("s:", s)

Output:

p is True
q is False
r: 4
s: 7

Special literals
Python contains one special literal, that is, 'None'. This special literal is used for defining a null variable. If
'None' is compared with anything else other than a 'None', it will return false.

Example:

1. word = None
2. print(word)

Output:

None

7) Explain Python Functions?

A function is a section of the program or a block of code that is written once and can be executed whenever
required in the program. A function is a block of self-contained statements which has a valid name, parameters
list, and body. Functions make programming more functional and modular to perform modular tasks. Python
provides several built-in functions to complete tasks and also allows a user to create new functions as well.

There are three types of functions:

o Built-In Functions: copy(), len(), count() are the some built-in functions.

o User-defined Functions: Functions which are defined by a user known as user-defined functions.

o Anonymous functions: These functions are also known as lambda functions because they are not
declared with the standard def keyword.

Example: A general syntax of user defined function is given below.

1. def function_name(parameters list):


2. #--- statements---
3. return a_value

8) What is zip() function in Python?

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an
iterable, convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of
tuples.

Signature

1. zip(iterator1, iterator2, iterator3 ...)

Parameters
iterator1, iterator2, iterator3: These are iterator objects that are joined together.

Return

It returns an iterator from two or more iterators.

Note: If the given lists are of different lengths, zip stops generating tuples when the first list ends. It means
two lists are having 3, and 5 lengths will create a 3-tuple.

9) What is Python's parameter passing mechanism?

There are two parameters passing mechanism in Python:

o Pass by references

o Pass by value

By default, all the parameters (arguments) are passed "by reference" to the functions. Thus, if you change the
value of the parameter within a function, the change is reflected in the calling function as well. It indicates the
original variable. For example, if a variable is declared as a = 10, and passed to a function where it's value is
modified to a = 20. Both the variables denote to the same value.

The pass by value is that whenever we pass the arguments to the function only values pass to the function, no
reference passes to the function. It makes it immutable that means not changeable. Both variables hold the
different values, and original value persists even after modifying in the function.

Python has a default argument concept which helps to call a method using an arbitrary number of arguments.

10) How to overload constructors or methods in Python?


Python's constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__()
is automatically invoked by python to initialize members of an object. We can't overload constructors or
methods in Python. It shows an error if we try to overload.

Example:

1. class student:
2. def __init__(self, name):
3. self.name = name
4. def __init__(self, name, email):
5. self.name = name
6. self.email = email
7.
8. # This line will generate an error
9. #st = student("rahul")
10.
11. # This line will call the second constructor
12. st = student("rahul", "[email protected]")
13. print("Name: ", st.name)
14. print("Email id: ", st.email)

Output:

Name: rahul
Email id: [email protected]

11) What is the difference between remove() function and del statement?

The user can use the remove() function to delete a specific object in the list.

Example:

1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. list_1.remove(3)
4. print("After removal: ", list_1)

Output:

[3, 5, 7, 3, 9, 3]
After removal: [5, 7, 3, 9, 3]
If you want to delete an object at a specific location (index) in the list, you can either use del or pop.

Example:

1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. del list_1[2]
4. print("After deleting: ", list_1)

Output:

[3, 5, 7, 3, 9, 3]
After deleting: [3, 5, 3, 9, 3]
Note: You don't need to import any extra module to use these functions for removing an element from the
list.

We cannot use these methods with a tuple because the tuple is different from the list.

12) What is swapcase() function in the Python?

It is a string's function which converts all uppercase characters into lowercase and vice versa. It is used to alter
the existing case of the string. This method creates a copy of the string which contains all the characters in the
swap case. If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores
all the non-alphabetic characters. See an example below.

Example:

1. string = "IT IS IN LOWERCASE."


2. print(string.swapcase())
3.
4. string = "it is in uppercase."
5. print(string.swapcase())

Output:

it is in lowercase.
IT IS IN UPPERCASE.

13) How to remove whitespaces from a string in Python?

To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function.
This function returns a copy of the string after removing whitespaces if present. Otherwise returns original
string.
Example:

1. string = " javatpoint "


2. string2 = " javatpoint "
3. string3 = " javatpoint"
4. print(string)
5. print(string2)
6. print(string3)
7. print("After stripping all have placed in a sequence:")
8. print(string.strip())
9. print(string2.strip())
10. print(string3.strip())

Output:

javatpoint
javatpoint
javatpoint
After stripping all have placed in a sequence:
Javatpoint
javatpoint
javatpoint

14) How to remove leading whitespaces from a string in the Python?

To remove leading characters from a string, we can use lstrip() function. It is Python string function which takes
an optional char type parameter. If a parameter is provided, it removes the character. Otherwise, it removes all
the leading spaces from the string.

Example:

1. string = " javatpoint "


2. string2 = " javatpoint "
3. print(string)
4. print(string2)
5. print("After stripping all leading whitespaces:")
6. print(string.lstrip())
7. print(string2.lstrip())

Output:
javatpoint
javatpoint
After stripping all leading whitespaces:
javatpoint
javatpoint

After stripping, all the whitespaces are removed, and now the string looks like the below:

15) Why do we use join() function in Python?

The join() is defined as a string method which returns a string value. It is concatenated with the elements of an
iterable. It provides a flexible way to concatenate the strings. See an example below.

Example:

1. str = "Rohan"
2. str2 = "ab"
3. # Calling function
4. str2 = str.join(str2)
5. # Displaying result
6. print(str2)

Output:

aRohanb

16) Give an example of shuffle() method?

This method shuffles the given string or an array. It randomizes the items in the array. This method is present
in the random module. So, we need to import it and then we can call the function. It shuffles elements each time
when the function calls and produces different output.

Example:

1. # import the random module


2. import random
3. # declare a list
4. sample_list1 = ['Z', 'Y', 'X', 'W', 'V', 'U']
5. print("Original LIST1: ")
6. print(sample_list1)
7. # first shuffle
8. random.shuffle(sample_list1)
9. print("\nAfter the first shuffle of LIST1: ")
10. print(sample_list1)
11. # second shuffle
12. random.shuffle(sample_list1)
13. print("\nAfter the second shuffle of LIST1: ")
14. print(sample_list1)

Output:

Original LIST1:
['Z', 'Y', 'X', 'W', 'V', 'U']

After the first shuffle of LIST1:


['V', 'U', 'W', 'X', 'Y', 'Z']

After the second shuffle of LIST1:


['Z', 'Y', 'X', 'U', 'V', 'W']

17) What is the use of break statement?

The break statement is used to terminate the execution of the current loop. Break always breaks the current
execution and transfer control to outside the current block. If the block is in a loop, it exits from the loop, and if
the break is in a nested loop, it exits from the innermost loop.

Example:

1. list_1 = ['X', 'Y', 'Z']


2. list_2 = [11, 22, 33]
3. for i in list_1:
4. for j in list_2:
5. print(i, j)
6. if i == 'Y' and j == 33:
7. print('BREAK')
8. break
9. else:
10. continue
11. break

Output:

2
X 11
X 22
X 33
Y 11
Y 22
Y 33
BREAK

Python Break statement flowchart.


18) What is tuple in Python?

A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change
is reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot
remove any element but can find in the tuple. We can use indexing to get elements. It also allows traversing
elements in reverse order by using negative indexing. Tuple supports various methods like max(), sum(),
sorted(), Len() etc.

To create a tuple, we can declare it as below.

Example:

1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])

Output:

(2, 4, 6, 8)
6

It is immutable. So updating tuple will lead to an error.

Example:

1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])
8.
9. # Updating by assigning new value
10. tup[2]=22
11. # Displaying Single value
12. print(tup[2])

Output:

tup[2]=22
TypeError: 'tuple' object does not support item assignment
(2, 4, 6, 8)

19) Which are the file related libraries/modules in Python?

The Python provides libraries/modules that enable you to manipulate text files and binary files on the file
system. It helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and
shutil.

Here, os and os.path - modules include a function for accessing the filesystem

while shutil - module enables you to copy and delete the files.

20) What are the different file processing modes supported by Python?

Python provides four modes to open files. The read-only (r), write-only (w), read-write (rw) and append mode
(a). 'r' is used to open a file in read-only mode, 'w' is used to open a file in write-only mode, 'rw' is used to open
in reading and write mode, 'a' is used to open a file in append mode. If the mode is not specified, by default file
opens in read-only mode.

o Read-only mode (r): Open a file for reading. It is the default mode.

o Write-only mode (w): Open a file for writing. If the file contains data, data would be lost. Other a new
file is created.

o Read-Write mode (rw): Open a file for reading, write mode. It means updating mode.

o Append mode (a): Open for writing, append to the end of the file, if the file exists.

21) What is an operator in Python?

An operator is a particular symbol which is used on some values and produces an output as a result. An operator
works on operands. Operands are numeric literals or variables which hold some values. Operators can be
unary, binary or ternary. An operator which requires a single operand known as a unary operator, which
require two operands known as a binary operator and which require three operands is called ternary
operator.

Example:

1. # Unary Operator
2. A = 12
3. B = -(A)
4. print (B)
5. # Binary Operator
6. A = 12
7. B = 13
8. print (A + B)
9. print (B * A)
10. #Ternary Operator
11. A = 12
12. B = 13
13. min = A if A < B else B
14.
15. print(min)

Output:

# Unary Operator
-12
# Binary Operator
25
156
# Ternary Operator
12

22) What are the different types of operators in Python?

Python uses a rich set of operators to perform a variety of operations. Some individual operators like
membership and identity operators are not so familiar but allow to perform operations.

o Arithmetic OperatorsRelational Operators

o Assignment Operators

o Logical Operators

o Membership Operators

o Identity Operators

o Bitwise Operators
Arithmetic operators perform basic arithmetic operations. For example "+" is used to add and "?" is used for
subtraction.

Example:

1. # Adding two values


2. print(12+23)
3. # Subtracting two values
4. print(12-23)
5. # Multiplying two values
6. print(12*23)
7. # Dividing two values
8. print(12/23)

Output:

35
-11
276
0.5217391304347826

Relational Operators are used to comparing the values. These operators test the conditions and then returns
a boolean value either True or False.

# Examples of Relational Operators

Example:
1. a, b = 10, 12
2. print(a==b) # False
3. print(a<b) # True
4. print(a<=b) # True
5. print(a!=b) # True

Output:

False
True
True
True

Assignment operators are used to assigning values to the variables. See the examples below.

Example:

1. # Examples of Assignment operators


2. a=12
3. print(a) # 12
4. a += 2
5. print(a) # 14
6. a -= 2
7. print(a) # 12
8. a *=2
9. print(a) # 24
10. a **=2
11. print(a) # 576

Output:

12
14
12
24
576

Logical operators are used to performing logical operations like And, Or, and Not. See the example below.

Example:

1. # Logical operator examples


2. a = True
3. b = False
4. print(a and b) # False
5. print(a or b) # True
6. print(not b) # True

Output:

False
True
True

Membership operators are used to checking whether an element is a member of the sequence (list, dictionary,
tuples) or not. Python uses two membership operators in and not in operators to check element presence. See
an example.

Example:

1. # Membership operators examples


2. list = [2,4,6,7,3,4]
3. print(5 in list) # False
4. cities = ("india","delhi")
5. print("tokyo" not in cities) #True

Output:

False
True

Identity Operators (is and is not) both are used to check two values or variable which are located on the same
part of the memory. Two variables that are equal does not imply that they are identical. See the following
examples.

Example:

1. # Identity operator example


2. a = 10
3. b = 12
4. print(a is b) # False
5. print(a is not b) # True

Output:
False
True

Bitwise Operators are used to performing operations over the bits. The binary operators (&, |, OR) work on
bits. See the example below.

Example:

1. # Identity operator example


2. a = 10
3. b = 12
4. print(a & b) # 8
5. print(a | b) # 14
6. print(a ^ b) # 6
7. print(~a) # -11

Output:

8
14
6
-11

23) How to create a Unicode string in Python?

In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We
can make a string in Unicode by using art.title.encode("utf-8") function.

Example:

1. unicode_1 = ("\u0123", "\u2665", "\U0001f638", "\u265E", "\u265F", "\u2168")


2. print (unicode_1)

Output:

unicode_1: ('ģ', '♥', '😸', '♞', '♟', 'Ⅸ')

24) is Python interpreted language?

Python is an interpreted language. The Python language program runs directly from the source code. It converts
the source code into an intermediate language code, which is again translated into machine language that has
to be executed.
Unlike Java or C, Python does not require compilation before execution.

25) How is memory managed in Python?

Memory is managed in Python in the following ways:

o Memory management in python is managed by Python private heap space. All Python objects and data
structures are located in a private heap. The programmer does not have access to this private heap.
The python interpreter takes care of this instead.

o The allocation of heap space for Python objects is done by Python's memory manager. The core API
gives access to some tools for the programmer to code.

o Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can
be made available to the heap space.

26) What is the Python decorator?

Decorators are very powerful and a useful tool in Python that allows the programmers to add functionality to
an existing code. This is also called metaprogramming because a part of the program tries to modify another
part of the program at compile time. It allows the user to wrap another function to extend the behaviour of the
wrapped function, without permanently modifying it.

Example:

1. def function_is_called():
2. def function_is_returned():
3. print("JavaTpoint")
4. return function_is_returned
5. new_1 = function_is_called()
6. # Outputs "JavaTpoint"
7. new_1()

Output:

JavaTpoint

Functions vs. Decorators

A function is a block of code that performs a specific task whereas a decorator is a function that modifies other
functions.

27) What are the rules for a local and global variable in Python?

Global Variables:

o Variables declared outside a function or in global space are called global variables.

o If a variable is ever assigned a new value inside the function, the variable is implicitly local, and we
need to declare it as 'global' explicitly. To make a variable globally, we need to declare it by using global
keyword.

o Global variables are accessible anywhere in the program, and any function can access and modify its
value.

Example:

1. A = "JavaTpoint"
2. def my_function():
3. print(A)
4. my_function()

Output:

JavaTpoint

Local Variables:

o Any variable declared inside a function is known as a local variable. This variable is present in the local
space and not in the global space.
o If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local.

o Local variables are accessible within local body only.

Example:

1. def my_function2():
2. K = "JavaTpoint Local"
3. print(K)
4. my_function2()

Output:

JavaTpoint Local

28) What is the namespace in Python?

The namespace is a fundamental idea to structure and organize the code that is more useful in large projects.
However, it could be a bit difficult concept to grasp if you're new to programming. Hence, we tried to make
namespaces just a little easier to understand.

A namespace is defined as a simple system to control the names in a program. It ensures that names are unique
and won't lead to any conflict.

Also, Python implements namespaces in the form of dictionaries and maintains name-to-object mapping where
names act as keys and the objects as values.

29) What are iterators in Python?

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of
items, and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and next() method to iterate
the stored elements. In Python, we generally use loops to iterate over the collections (list, tuple).

In simple words: Iterators are objects which can be traversed though or iterated upon.

30) What is a generator in Python?

In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that
it yields expression in the function. It does not implements __itr__ and next() method and reduce other
overheads as well.

If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current
execution by saving its states and then resume from the same when required.
31) What is slicing in Python?

Slicing is a mechanism used to select a range of items from sequence type like list, tuple, and string. It is
beneficial and easy to get elements from a range by using slice way. It requires a : (colon) which separates the
start and end index of the field. All the data collection types List or tuple allows us to use slicing to fetch
elements. Although we can get elements by specifying an index, we get only single element whereas using
slicing we can get a group of elements.

Example:

1. Q = "JavaTpoint, Python Interview Questions!"


2. print(Q[2:25])

Output:

vaTpoint, Python Interv

32) What is a dictionary in Python?

The Python dictionary is a built-in data type. It defines a one-to-one relationship between keys and values.
Dictionaries contain a pair of keys and their corresponding values. It stores elements in key and value pairs.
The keys are unique whereas values can be duplicate. The key accesses the dictionary elements.

Keys index dictionaries.

Example:

The following example contains some keys Country Hero & Cartoon. Their corresponding values are India,
Modi, and Rahul respectively.

1. dict = {'Country': 'India', 'Hero': 'Modi', 'Cartoon': 'Rahul'}


2. print ("Country: ", dict['Country'])
3. print ("Hero: ", dict['Hero'])
4. print ("Cartoon: ", dict['Cartoon'])

Output:

Country: India
Hero: Modi
Cartoon: Rahul

33) What is Pass in Python?

Pass specifies a Python statement without operations. It is a placeholder in a compound statement. If we want
to create an empty class or functions, the pass keyword helps to pass the control without error.

Example:

1. class Student:
2. pass # Passing class
3. class Student:
4. def info():
5. pass # Passing function

34) Explain docstring in Python?

The Python docstring is a string literal that occurs as the first statement in a module, function, class, or method
definition. It provides a convenient way to associate the documentation.

String literals occurring immediately after a simple assignment at the top are called "attribute docstrings".

String literals occurring immediately after another docstring are called "additional docstrings".

Python uses triple quotes to create docstrings even though the string fits on one line.

Docstring phrase ends with a period (.) and can be multiple lines. It may consist of spaces and other special
chars.

Example:

1. # One-line docstrings
2. def hello():
3. """A function to greet."""
4. return "hello"
35) What is a negative index in Python and why are they used?

The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers
that are positive uses '0' that is uses as first index and '1' as the second index and the process go on like that.

The index for the negative number starts from '-1' that represents the last index in the sequence and '-2' as the
penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last
character that is given as S[:-1]. The negative index is also used to show the index to represent the string in
correct order.

36) What is pickling and unpickling in Python?

The Python pickle is defined as a module which accepts any Python object and converts it into a string
representation. It dumps the Python object into a file using the dump function; this process is called Pickling.

The process of retrieving the original Python objects from the stored string representation is called
as Unpickling.

37) Which programming language is a good choice between Java and Python?

Java and Python both are object-oriented programming languages. Let's compare both on some criteria given
below:

Criteria Java Python

Ease of use Good Very Good

Coding Speed Average Excellent

Data types Static type Dynamic type

Data Science and Machine learning application Average Very Good

38) What is the usage of help() and dir() function in Python?

Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated
dump of built-in functions.
Help() function: The help() function is used to display the documentation string and also facilitates us to see
the help related to modules, keywords, and attributes.

Dir() function: The dir() function is used to display the defined symbols.

39) What are the differences between Python 2.x and Python 3.x?

Python 2.x is an older version of Python. Python 3.x is newer and latest version. Python 2.x is legacy now. Python
3.x is the present and future of this language.

The most visible difference between Python2 and Python3 is in print statement (function). In Python 2, it looks
like print "Hello", and in Python 3, it is print ("Hello").

String in Python2 is ASCII implicitly, and in Python3 it is Unicode.

The xrange() method has removed from Python 3 version. A new keyword as is introduced in Error handling.

40) How Python does Compile-time and Run-time code checking?

In Python, some amount of coding is done at compile time, but most of the checking such as type, name, etc. are
postponed until code execution. Consequently, if the Python code references a user-defined function that does
not exist, the code will compile successfully. The Python code will fail only with an exception when the code
execution path does not exist.

41) What is the shortest method to open a text file and display its content?

The shortest way to open a text file is by using "with" command in the following manner:

Example:

1. with open("FILE NAME", "r") as fp:


2. fileData = fp.read()
3. # To print the contents of the file
4. print(fileData)

Output:

"The data of the file will be printed."

42) What is the usage of enumerate () function in Python?


The enumerate() function is used to iterate through the sequence and retrieve the index position and its
corresponding value at the same time.

Example:

1. list_1 = ["A","B","C"]
2. s_1 = "Javatpoint"
3. # creating enumerate objects
4. object_1 = enumerate(list_1)
5. object_2 = enumerate(s_1)
6.
7. print ("Return type:",type(object_1))
8. print (list(enumerate(list_1)))
9. print (list(enumerate(s_1)))

Output:

Return type:
[(0, 'A'), (1, 'B'), (2, 'C')]
[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7, 'i'), (8, 'n'), (9, 't')]

43) Give the output of this example: A[3] if A=[1,4,6,7,9,66,4,94].

Since indexing starts from zero, an element present at 3rd index is 7. So, the output is 7.

44) What is type conversion in Python?

Type conversion refers to the conversion of one data type iinto another.

int() - converts any data type into integer type

float() - converts any data type into float type

ord() - converts characters into integer

hex() - converts integers to hexadecimal

oct() - converts integer to octal

tuple() - This function is used to convert to a tuple.

set() - This function returns the type after converting to set.


list() - This function is used to convert any data type to a list type.

dict() - This function is used to convert a tuple of order (key,value) into a dictionary.

str() - Used to convert integer into a string.

complex(real,imag) - This functionconverts real numbers to complex(real,imag) number.

45) How to send an email in Python Language?

To send an email, Python provides smtplib and email modules. Import these modules into the created mail
script and send mail by authenticating a user.

It has a method SMTP(smtp-server, port). It requires two parameters to establish SMTP connection.

A simple example to send an email is given below.

Example:

1. import smtplib
2. # Calling SMTP
3. s = smtplib.SMTP('smtp.gmail.com', 587)
4. # TLS for network security
5. s.starttls()
6. # User email Authentication
7. s.login("sender@email_id", "sender_email_id_password")
8. # Message to be sent
9. message = "Message_sender_need_to_send"
10. # Sending the mail
11. s.sendmail("sender@email_id ", "receiver@email_id", message)

46) What is the difference between Python Arrays and lists?

Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type
elements whereas lists can hold any data type elements.

Example:

1. import array as arr


2. User_Array = arr.array('i', [1,2,3,4])
3. User_list = [1, 'abc', 1.20]
4. print (User_Array)
5. print (User_list)

Output:

array('i', [1, 2, 3, 4])


[1, 'abc', 1.2]

47) What is lambda function in Python?

The anonymous function in python is a function that is defined without a name. The normal functions are
defined using a keyword "def", whereas, the anonymous functions are defined using the lambda function. The
anonymous functions are also called as lambda functions.

48) Why do lambda forms in Python not have the statements?

Lambda forms in Python does not have the statement because it is used to make the new function object and
return them in runtime.

49) What are functions in Python?

A function is a block of code which is executed only when it is called. To define a Python function, the def
keyword is used.

Example:

1. def New_func():
2. print ("Hi, Welcome to JavaTpoint")
3. New_func() #calling the function

Output:

Hi, Welcome to JavaTpoint

50) What is __init__?

The __init__ is a method or constructor in Python. This method is automatically called to allocate memory when
a new object/ instance of a class is created. All classes have the __init__ method.
Example:

1. class Employee_1:
2. def __init__(self, name, age,salary):
3. self.name = name
4. self.age = age
5. self.salary = 20000
6. E_1 = Employee_1("pqr", 20, 25000)
7. # E1 is the instance of class Employee.
8. #__init__ allocates memory for E1.
9. print(E_1.name)
10. print(E_1.age)
11. print(E_1.salary)

Output:

pqr
20
25000

51) What is self in Python?

Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However,
this is not the case in Java where it's optional. It helps to differentiate between the methods and attributes of a
class with local variables.

The self-variable in the init method refers to the newly created object while in other methods, it refers to the
object whose method was called.

52) How can you generate random numbers in Python?

Random module is the standard module that is used to generate a random number. The method is defined as:

1. import random
2. random.random

The statement random.random() method return the floating point number that is in the range of [0, 1). The
function generates random float numbers. The methods that are used with the random class are the bound
methods of the hidden instances. The instances of the Random can be done to show the multi-threading
programs that creates a different instance of individual threads. The other random generators that are used in
this are:
randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by
selecting it randomly from the range that is specified. It doesn't build a range object.

uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating
point number

normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a
sigma that is used for standard deviation.

The Random class that is used and instantiated creates independent multiple random number generators.

53) What is PYTHONPATH?

PYTHONPATH is an environment variable which is used when a module is imported. Whenever a module is
imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various
directories. The interpreter uses it to determine which module to load.

54) What are python modules? Name some commonly used built-in modules in Python?

Python modules are files containing Python code. This code can either be functions classes or variables. A
Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:

o os

o sys

o math

o random

o data time

o JSON

55) What is the difference between range & xrange?

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to
generate a list of integers for you to use, however you please. The only difference is that range returns a Python
list object and x range returns an xrange object.

This means that xrange doesn't actually generate a static list at run-time like range does. It creates the values
as you need them with a special technique called yielding. This technique is used with a type of object known
as generators. That means that if you have a really gigantic range you'd like to generate a list for, say one billion,
xrange is the function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working
with, as range will use as much memory as it can to create your array of integers, which can result in a Memory
Error and crash your program. It's a memory hungry beast.

56) What advantages do NumPy arrays offer over (nested) Python lists?

o Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion,
deletion, appending, and concatenation, and Python's list comprehensions make them easy to
construct and manipulate.

o They have certain limitations: they don't support "vectorized" operations like elementwise addition
and multiplication, and the fact that they can contain objects of differing types mean that Python must
store type information for every element, and must execute type dispatching code when operating on
each element.

o NumPy is not just more efficient; it is also more convenient. We get a lot of vector and matrix
operations for free, which sometimes allow one to avoid unnecessary work. And they are also
efficiently implemented.

o NumPy array is faster and we get a lot built in with NumPy, FFTs, convolutions, fast searching, basic
statistics, linear algebra, histograms, etc.

57) Mention what the Django templates consist of.

The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template
contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control
the logic of the template.
58) Explain the use of session in Django framework?

Django provides a session that lets the user store and retrieve data on a per-site-visitor basis. Django abstracts
the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all
the related data on the server side.

So, the data itself is not stored client side. This is good from a security perspective.

Interview based Multiple Choice Questions on Python

1) Which of the following statements is/are TRUE in respect of the Python programming language?

Statement 1: Python is an interpreted, high-level, general-purpose programming language.

Statement 2: Python provides high-level data structures along with dynamic binding and typing for Rapid
Application Development and deployment.

Statement 3: Python is a Statically typed Programming language.

Options:

a. Only Statement 1

b. Statement 1 and 2

c. Statement 1 and 3

d. All Statements are Correct

2) What is the full form of PEP?

Options:

a. Python Enhancement Proposal

b. Python Enchantment Proposal

c. Programming Enhancement Proposition


d. Python Enrichment Program

3) Which of the following statements is/are NOT correct regarding Memory Management in Python?

Statement 1: Python Memory Manager handles the management regarding memory in Python

Statement 2: Python uses CMS (Concurrent Mark Sweep) approach as its Garbage Collection technique.

Statement 3: Python offers a core garbage collection to recycle the vacant memory for the private heap space.

Options:

a. Only Statement 3

b. Statement 1 and 3

c. Statement 2 and 3

d. Only Statement 2

4) Which of the following statements is/are NOT correct in respect to Python namespaces?

Statement 1: Python implements the namespace in the form of Array.

Statement 2: Python namespaces are classified into three types - local, global and built-in.

Statement 3: A Python namespace ensures that the names of the objects in a program are unique and can be
utilized, deprived of any inconsistency.

Options:

a. Only Statement 1

b. Only Statement 3

c. Statement 1 and 2

d. Statement 1 and 3

5) Which of the following is invalid in terms of Variable Names?

Options:

a. _mystr = "Hello World!"

b. __mystr = "Hello World!"

c. __mystr__ = "Hello World!"

d. None of the mentioned


Show Answer Workspace

6) In respect to the scope in Python, which of the following statements is/are TRUE?

Statement 1: A variable created within a function belongs to the local scope and can be used outside that
function.

Statement 2: A local scope is referred to the object present through the execution of code since its inception.

Statement 3: A local scope is referred to the local object present in the current function.

Options:

a. Only Statement 2

b. Statement 1 and 3

c. Only Statement 3

d. All Statements are True

Show Answer Workspace

7) What will the following snippet of code print?

Code:

1. # assigning a variable
2. myint = 10
3.
4. # defining a function
5. def myfunction():
6. # reassigning a variable
7. myint = 20
8.
9. # calling the function
10. myfunction()
11.
12. # printing the value of the variable
13. print(myint)

Options:

a. 10
b. 20

c. 0

d. Traceback Error

Show Answer Workspace

8) What will the following snippet of code yield?

Code:

1. # assigning a variable
2. myint = 21
3.
4. # using if False statement
5. if False:
6. # reassigning a variable
7. myint = 34
8.
9. # defining a function
10. def myfunction():
11. if True:
12. # reassigning a variable
13. myint = 65
14.
15. # calling the function
16. myfunction()
17.
18. # printing the value of the variable
19. print(myint)

Options:

a. 65

b. Traceback Error

c. 21

d. 34
Show Answer Workspace

9) Among the following statements based on the difference between lists and tuples, which one statement is
TRUE?

Statement 1: List is a sequence data structure, whereas Tuple is not.

Statement 2: Lists are immutable; however, Tuples are mutable.

Statement 3: Tuple is a sequence data structure, whereas List is not.

Statement 4: Tuples are immutable; however, Lists are mutable.

Options:

a. Statement 1

b. Statement 4

c. Statement 2

d. Statement 3

Show Answer Workspace

10) What will be the output of the following snippet of code?

Code:

1. # defining a list
2. my_list = [7, 9, 8, 2, 5, 0, 1, 3, 6]
3. # using the pop() function
4. my_list.pop(2)
5. # printing the final list
6. print(my_list)

Options:

a. [7, 9, 2, 5, 0, 1, 3, 6]

b. [7, 9, 8, 2, 5, 0, 3, 6]

c. [7, 8, 2, 5, 0, 1, 3, 6]

d. [7, 9, 8, 2, 5, 0, 1, 6]
Python Basic Interview Questions

Following are the Basic Python Interview Questions For Freshers:

1. What is Python?

Python is a high-level and object-oriented programming language with unified semantics designed primarily
for developing apps and the web. It is the core language in the field of Rapid Application Development (RAD)
as it offers options such as dynamic binding and dynamic typing.

2. What are the benefits of Python?

The benefits of Python are as follows:

 Speed and Productivity: Utilizing the productivity and speed of Python will enhance the process
control capabilities and possesses strong integration.
 Extensive Support for Libraries: Python provides a large standard library that includes areas such
as operating system interfaces, web service tools, internet protocols, and string protocols. Most of the
programming tasks are already been scripted in the standard library which reduces effort and time.
 User-friendly Data Structures: Python has an in-built dictionary of data structures that are used to
build fast user-friendly data structures.
 Existence of Third Party Modules: The presence of third-party modules in the Python Package
Index (PyPI) will make Python capable to interact with other platforms and languages.
 Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for
beginners to learn.

3. What are the key features of Python?

The following are the significant features of Python, and they are:

 Interpreted Language: Python is an interpreted language that is used to execute the code line by
line at a time. This makes debugging easy.
 Highly Portable: Python can run on different platforms such as Unix, Macintosh, Linux, Windows,
and so on. So, we can say that it is a highly portable language.
 Extensible: It ensures that the Python code can be compiled on various other languages such as C,
C++, and so on.
 GUI programming Support: It implies that Python provides support to develop graphical user
interfaces

4. What type of language is Python? Programming or Scripting?

Python is suitable for scripting, but in general, it is considered a general-purpose programming language.

Top 10 Programming Languages that you need to watch out to boost your career in 2022

5. What are the applications of Python?

The applications of Python are as follows:

 GUI based desktop applications


 Image processing applications
 Business and Enterprise applications
 Prototyping
 Web and web framework applications

6. What is the difference between list and tuple in Python?

The difference between tuple and list is as follows:

List
Tuple

The list is mutable (can be changed) A tuple is immutable (remains constant)

These lists performance is slower Tuple performance is faster when compared to lists

Syntax: list_1 = [20, ‘Mindmajix’, 30] Syntax: tup_1 = (20, ‘Mindmajix’, 30)

7. What are the global and local variables in Python?

Global Variables in Python: The variables that are declared outside the function are called global variables.
These variables can be accessed or invoked by any function in the program.

Example:

def v() :
print g
g = "welcome to mindmajix"
v()

Output:

Welcome to mindmajix

Local Variables in Python: The variables that are declared inside a function are called local variables. These
types of variables can be accessed only inside the function.

8. Define PYTHON PATH?

PYTHONPATH is an environmental variable that is used when we import a module. Suppose at any time we
import a module, PYTHONPATH is used to check the presence of the modules that are imported in different
directories. Loading of the module will be determined by interpreters.

9. What are the two major loop statements?

for and while


10. What do you understand by the term PEP 8?

PEP 8 is the Python latest coding convention and it is abbreviated as Python Enhancement Proposal. It is all
about how to format your Python code for maximum readability.

11. How memory management is done in Python?

 In Python memory management is done using private heap space. The private heap is the storage
area for all the data structures and objects. The interpreter has access to the private heap and the
programmer cannot access this private heap.
 The storage allocation for the data structures and objects in Python is done by the memory manager.
The access for some tools is provided by core API for programmers to code.
 The built-in garbage collector in Python is used to recycle all the unused memory so that it can be
available for heap storage area.

12. Java vs Python

The major difference between Java and Python are as follows:

Function
Java Python

In Java, we need to write a long code to print In Python coding is simple and smaller when
Coding
something. compared to Java

In Java we need to put a semicolon at the end Whereas, in Python indentation is


Syntax of the statement and also code must be mandatory as it improves the readability of
placed in curly braces. the code.

In Java, we need to declare the type for each In this case, codes are dynamically typed and
Dynamic
variable this is also known as duck typing

Java is not easy to use because of its larger In Python, it is very easy to code and perform
Easy to use
coding very easily.

Java Database Connectivity (JDBC) is more In Python database access layers are weaker
Databases
popular and used most commonly. when compared to Java.
13. Define modules in Python?

The module is defined as a file that includes a set of various functions and Python statements that we want to
add to our application.

Example of creating a module:

In order to create a module first, we need to save the code that we want in a file with .py extension.

Save the module with module.py

def wishes(name):
Print("Hi, " + name)

14. What are the built-in types available in Python?

The built-in types in Python are as follows:

 Integer
 Complex numbers
 Floating-point numbers
 Strings
 Built-in functions

15. What are Python Decorators?

Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of
class or function.

An example for Python Decorator is:

@gfg_decorator
def hi_decorator():
print("Gfg")

16. How do we find bugs and statistical problems in Python?

We can detect bugs in python source code using a static analysis tool named PyChecker. Moreover, there is
another tool called PyLint that checks whether the Python modules meet their coding standards or not.

17. What is the difference between .py and .pyc files?

py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python
compiler
18. How do you invoke the Python interpreter for interactive use?

By using python or pythonx. y we can invoke a Python interpreter. where x.y is the version of the Python
interpreter.

19. Define String in Python?

String in Python is formed using a sequence of characters. Value once assigned to a string cannot be modified
because they are immutable objects. String literals in Python can be declared using double quotes or single
quotes.

Example:

print("Hi")
print('Hi')

20. What do you understand by the term namespace in Python?

A namespace in Python can be defined as a system that is designed to provide a unique name for every object
in python. Types of namespaces that are present in Python are:

 Local namespace
 Global namespace
 Built-in namespace

Scope of an object in Python:

Scope refers to the availability and accessibility of an object in the coding region.

21. How do you create a Python function?

Functions are defined using the def statement.

An example might be def foo(bar):

22. Define iterators in Python?

In Python, an iterator can be defined as an object that can be iterated or traversed upon. In another way, it is
mainly used to iterate a group of containers, elements, the same as a list.

23. How does a function return values?

Functions return values using the return statement.

24. Define slicing in Python?

Slicing is a procedure used to select a particular range of items from sequence types such as Strings, lists, and
so on.

25. How can Python be an interpreted language?


As in Python the code which we write is not machine-level code before runtime so, this is the reason why
Python is called an interpreted language.

26. What happens when a function doesn’t have a return statement? Is this valid?

Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of
code that is executed (i.e., the indenting) not by any explicit keyword.

27. Define package in Python?

In Python packages are defined as the collection of different modules.

28. How can we make a Python script executable on Unix?

In order to make a Python script executable on Unix, we need to perform two things. They are:

Script file mode must be executable and

The first line should always begin with #.

29. Which command is used to delete files in Python?

OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming.

Example:

import OS
OS.remove("abc.txt")

30. Define pickling and unpickling in Python?

Pickling in Python: The process in which the pickle module accepts various Python objects and converts
them into a string representation and dumps the file accordingly using the dump function is called pickling.

Unpickling in Python: The process of retrieving actual Python objects from the stored string representation
is called unpickling.

⇒ Learn about Basic Python Tutorial

31. Explain the difference between local and global namespaces?

Local namespaces are created within a function when that function is called. Global namespaces are created
when the program starts.

32. What is a boolean in Python?


Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false.

Python bool() is the method used to convert a value to a boolean value.

Syntax for bool() method: bool([a])

33. What are Python String formats and Python String replacements?

Python String Format: The String format() method in Python is mainly used to format the given string into an
accurate output or result.

Syntax for String format() method:

template.format(p0, p1, ..., k0=v0, k1=v1, ...)

Python String Replace: This method is mainly used to return a copy of the string in which all the occurrence of
the substring is replaced by another substring.

Syntax for String replace() method:

str.replace(old, new [, count])

34. Name some of the built-in modules in Python?

The built-in modules in Python are:

 sys module
 OS module
 random module
 collection module
 JSON
 Math module

35. What are the functions in Python?

In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is
used to define a function in Python.

Example:

def Func():
print("Hello, Welcome toMindmajix")
Func(); #calling the function

Output: Hello, Welcome to Mindmajix

36. What are Dict and List comprehensions in Python?

These are mostly used as syntax constructions to ease the creation of lists and dictionaries based on existing
iterable.
37. Define the term lambda?

Lambda is the small anonymous function in Python that is often used as an inline function.

38. When would you use triple quotes as a delimiter?

Triple quotes ‘’” or ‘“ are string delimiters that can span multiple lines in Python. Triple quotes are usually
used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained
therein.

39. Define self in Python?

In Python self is defined as an object or an instance of a class. This self is explicitly considered as the first
parameter in Python. Moreover, we can also access all the methods and attributes of the classes in Python
programming using self keyword.

In the case of the init method, self refers to the newer creation of the object. Whereas in the case of other
methods self refers to the object whose method was called.

40. What is _init_?

The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a
new object. The main role of _init_ is to initialize the values of instance members for objects.

Example:

class Student:
def _init_ (self, name, age, marks):
self.name = name
self.age = age
self.marks = 950
S1 = Student("ABC", 22, 950)
# S1 is the instance of class Student.
# _init allocates memory for S1.
print(S1.name)
print(S1.age)
print(S1.marks)

Output:

ABC
22
950

41. Define generators in Python?


The way of implementing an effective representation of iterators is known as generators. It is only the normal
function that yields expression in the function.

42. Define docstring in Python?

The docstring in Python is also called a documentation string, it provides a way to document the Python
classes, functions, and modules.

43. How do we convert the string to lowercase?

the lower() function is used to convert string to lowercase.

Example:

str = 'XYZ'
print(str.lower())
Output:
xyz

44. How to remove values from a Python array?

Ans: The elements can be removed from a Python array using the remove() or pop() function. The difference
between pop() and remove() will be explained in the below example.

Example:

x = arr.array('d', [ 1.0, 2.2, 3.4, 4.8, 5.2, 6.6, 7.3])


print(x.pop())
print(x.pop(3))
x.remove(1.0)
print(a)

Output:

7.3
4.8
array(‘d’, [2.2, 3.4, 5.2, 6.6])
For More Info: Array Example in Python

45. What is Try Block?


A block that is preceded by the try keyword is known as a try block

Syntax:

try{
//statements that may cause an exception
}

46. Why do we use the split method in Python?

split() method in Python is mainly used to separate a given string.

Example:

x = "Mindmajix Online Training"


print(a.split())
Output:
[‘Mindmajix’, ‘Online’, ‘Training’]

47. How can we access a module written in Python from C?

We can access the module written in Python from C by using the following method.

Module == PyImport_ImportModule("<modulename>");

48. How do you copy an object in Python?

To copy objects in Python we can use methods called copy.copy() or copy.deepcopy().

49. How do we reverse a list in Python?

By using the list.reverse(): we can reverse the objects of the list in Python.

Python Programming Interview Questions:

Following are the Python Programming Interview Questions with Answers

50. How can we debug a Python program?

By using the following command we can debug the Python program

$ python -m pdb python-script.py

51. Write a program to count the number of capital letters in a file?

with open(SOME_LARGE_FILE) as countletter:


count = 0
text = countletter.read()
for character in text:
if character.isupper():
count += 1

52. Write a program to display the Fibonacci sequence in Python?

# Displaying Fibonacci sequence


n = 10
# first two terms
n0 = 0
n1 = 1
#Count
x=0
# check if the number of terms is valid
if n <= 0:
print("Enter positive integer")
elif n == 1:
print("Numbers in Fibonacci sequence upto",n,":")
print(n0)
else:
print("Numbers in Fibonacci sequence upto",n,":")
while x < n:
print(n0,end=', ')
nth = n0 + n1
n0 = n1
n1 = nth
x += 1

Output:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

53. Write a program in Python to produce a Star triangle?

The code to produce a star triangle is as follows:

def pyfun(r):
for a in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfun(9)

Output:

*
***
*****
*******
*********
***********
*************
***************
*****************

54. Write a program to check whether the given number is prime or not?

The code to check prime number is as follows:

# program to check the number is prime or not


n1 = 409
# num1 = int(input("Enter any one number: "))
# prime number is greater than 1
if n1 > 1:
# check the following factors
for x is in range of(2,num1):
if (n1 % x) == 0:
print(n1,"is not a prime number")
print(x,"times",n1//x,"is",num)
break
else:
print(n1,"is a prime number")
# if input number is smaller than
# or equal to the value 1, then it is not prime number
else:
print(n1,"is not a prime number")

Output:

409 is a prime number

55. Write Python code to check the given sequence is a palindrome or not?
# Python code to check a given sequence
# is palindrome or not
my_string1 = 'MOM'
My_string1 = my_string1.casefold()
# reverse the given string
rev_string1 = reversed(my_string1)
# check whether the string is equal to the reverse of it or not
if list(my_string1) == list(rev_string1):
print("It is a palindrome")
else:
print("It is not a palindrome")

Output:

it is a palindrome

56. Write Python code to sort a numerical dataset?

The code to sort a numerical dataset is as follows:

list = [ "13", "16", "1", "5" , "8"]


list = [int(x) for x in the list]
list.sort()
print(list)

Output:

1, 5, 8, 13, 16

57. What is the output of the following code?

x = ['ab','cd']
print(list(map(list, x)))

The output of the following code is

[ [‘a’, ‘b’], [‘c’, ‘d’]

Python Developer Interview Questions

Following are Python Developer Interview Questions with Answers

58. What is the procedure to install Python on Windows and set path variables?

We need to implement the following steps to install Python on Windows, and they are:
 First, you need to install Python from https://www.python.org/downloads/
 After installing Python on your PC, find the place where it is located in your PC using the cmd python
command.
 Then visit advanced system settings on your PC and add a new variable. Name the new variable as
PYTHON_NAME then copy the path and paste it.
 Search for the path variable and select one of the values for it and click on ‘edit’.
 Finally, we need to add a semicolon at the end of the value, and if the semicolon is not present then
type %PYTHON_NAME%.

Check out Top Python Project Ideas For Practice

59. Differentiate between SciPy and NumPy?

The difference between SciPy and NumPy is as follows:

NumPy
SciPy

Numerical Python is called NumPy Scientific Python is called SciPy

It is used for performing general and efficient computations on numerical This is an entire collection of tools in Python mainl
data which is saved in arrays. For example, indexing, reshaping, sorting, perform operations like differentiation, integration
and so on many more.

There are some of the linear algebraic functions present in this module For performing algebraic computations this modul
but they are not fully-fledged. contains some of the fully-fledged operations

60. How do Python arrays and lists differ from each other?

The difference between Python array and Python list is as follows:

Arrays
Lists

The array is defined as a linear structure that is used to store only


The list is used to storing arbitrary and heterogeneous dat
homogeneous data.

Since array stores only a similar type of data so it occupies less List stores different types of data so it requires a huge amo
amount of memory when compared to the list. memory

The length of the array is fixed at the time of designing and no more The length of the list is no fixed, and adding items in the m
elements can be added in the middle. possible in lists.
61. Can we make multi-line comments in Python?

In python, there is no specific syntax to display multi-line comments like other languages. In order to display
multi-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not
used as the first statement in the present method, it will not be considered by the Python parser.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!

62. What is the difference between range and xrange?

Both the methods are mainly used in Python to iterate the for loop for a fixed number of times. They differ
only when we talk regarding Python versions.

The difference between range and xrange is as follows:

Range() method
Xrange() method

The xrange() method is not supported in Python3 so that the The xrange() method is used only in Python version 2 for t
range() method is used for iteration in for loops. iteration in loops.

It only returns the generator object because it doesn’t prod


The list is returned by this range() method
static list during run time.

It occupies a huge amount of memory as it stores the complete list It occupies less memory because it only stores one number
of iterating numbers in memory. in memory.

Python Advanced Interview Questions

Following are the Python Advanced Interview Questions with Answers

63. What is Django?


Django is an advanced python web framework that supports agile growth and clean pragmatic design, built
through experienced developers, this cares much about the trouble of web development, so you can
concentrate on writing your app without wanting to reinvent that wheel.

Related Article: Django Interview Questions for Experienced

64. List the features of Django?

 Excellent documentation
 Python web framework
 SEO optimized
 High scalability
 Versatile in nature
 Offers high security
 Thoroughly tested
 Provides rapid Development

65. Which level framework does Django belong to?

Django is a high-level Python web framework that was developed for realistic design, clean, rapid
development.

66. What are the advantages of Django?

 One of the important advantages of Django is it is a framework of python language which is very
simple to learn
 Django is a multifaceted framework
 When it comes to security Django is the best framework
 Scalability is added advantage of Django

67. Why should we use the Django framework?

The main goal to designing Django is to make it simple to its users, to do this Django uses:

 The principles concerning rapid development, which implies developers can complete more than one
iteration at a time without beginning the full schedule from scratch;
 DRY philosophy — Do not Replicate Yourself — that means developers can reuse surviving code and
also focus on the individual one.

Visit here to learn Python Training in Bangalore

68. List the common security issues that can be avoided by using Django?

A few common security issues that can be avoided by using Django are:

 Clickjacking
 Cross-site scripting and
 SQL injection
69. List a few of the famous companies that are using Django?

Few well-known companies that are using the Django framework are

 Instagram
 Spotify
 Mozilla
 Dropbox
 NASA

70. What can we do with the Django framework?

Here is an exciting reality: Django has first created to power a web application as a newspaper publisher, the
Lawrence Journal-World. You all can demand it to be very good about handling projects by volumes from the
text files, media, including extremely high traffic, or else something that operates as a web publication.

71. List steps for setting up static files in Django?

Ans: There are only three main steps for setting up Django static files

 Firstly set STATIC_ROOT in settings.py


 Run manage.py collect static
 Setting up a static file entry pythonAnywhere tab

72. Is Django stable?

Yes, Django is used by many famous companies because it is quite stable.

73. Differentiate Django reusability code with other frameworks?

Django web framework is operated and also maintained by an autonomous and non-profit organization
designated as Django Software Foundation (DSF). The initial foundation goal is to promote, support, and
advance this Django Web framework.

74. How can we handle URLs in Django?

from django.contrib import admin

from django.urls import path

urlpatterns = [

path('appmajix/', appmajix.site.urls),

75. List the mandatory files of the Django project?


 manage.py
 settings.py
 __init__.py
 urls.py
 wsgi.py

76. Explain the Django session?

A session comprises a mechanism to store information on a specific server-side at the interaction by the web
application. By default, session reserves in the database and allows file-based and cache-based sessions.

77. Why do we use a cookie in Django?

A cookie is a piece of information that is stored in a client's browser for a specific time. When the specific time
is completed cookie gets automatically removed from the client browser.

78. Mentions the methods used for setting and getting cookie values?

The two methods to set and get cookie values are

 Set_cookie this method is used to set the values of the cookie


 Get_cookie this method is used to get the values of the cookie

79. What is the use of Django-admin.py?

Django-admin.py is a command-line argument that is utilized for administrative tasks

80. What is the use of manage.py?

It is an automatically built file inside each Django project. It is a flat wrapper encompassing the Django-
admin.py. It possesses the following usage:

 It establishes your project's package on sys.path.


 It fixes the DJANGO_SETTING_MODULE environment variable to point to your project's setting.py file.

81. Why is Django loosely packed?

Django has described as a loosely coupled framework because of the MTV architecture it’s based upon.
Django’s architecture means a variant of MVC architecture and also MTV is helpful because this completely
separates the server code of the client’s machine.

82. List the ways we add view functions to urls.py?

 Adding a function view


 Adding a class-based view

83. Explain how can we build or set up the database in Django?

we can make use of the edit mysite/setting.py command, which is a simple Python module that consists of
levels for presenting or displaying Django settings.
By default Django uses SQLite; this also makes it easy for Django users in case of any other type of
installations. For example, if your database choice is different then you need to follow certain keys in the
DATABASE like default items to match database connection settings.

 Engines: By these engines you change the database by using commands such as
‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.sqlite3’, ‘django.db.backends.oracle’,
‘django.db.backends.mysql’, and so on.
 Name: This represents the name of your own database. If you are familiar with using SQLite as your
database, in such cases database is available as a file on your particular system. Moreover, the name
should be as a fully absolute or exact path along with the file name of the particular file.
 Suppose if we are not using SQLite as your database then additional settings such as password, user,
the host must be added.

Django mainly uses SQLite as its default database to store entire information in a single file of the filesystem.
If you want to use different database servers rather than SQLite, then make use of database administration
tools to create a new database for the Django project. Another way is by using your own database in that
place, and the remaining is to explain Django about how to use it. This is the place in which Python’s project
settings.py file comes into the picture.

We need to add the below code to the setting.py file:

DATABASE = {
‘Default’ : {
‘ENGINE’ : ‘django.db.backends.sqlite3’,
‘NAME’ : os.path.join(BASE_DIR, ‘db.sqlite3’),
}
}

84. List out the inheritance styles in Django?

There are three possible inheritance styles in Django, and they are:

 Proxy models: This style is mainly used for those who want to modify the Python level behavior of
the model, without modifying the model’s fields.
 Abstract Base Classes: This inheritance style is used only when we want to make parent class hold
the data which they don’t want to repeat again in the child class.
 Multi-table Inheritance: This inheritance style is used only when we want to subclass an existing
model and there must a database table designed for each model on its own.

85. How to save an image locally using Python in which we already know the URL address?

The following code is used to save the image locally from the URL address which we know.

import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")

86. How can we access sessions in flask?


A session will basically allow us to remember information from one request to another. In a flask, a signed
cookie is used to make the user look at the session contents and modify them. Moreover, the user can change
the session only when the secret key named Flask.secret_key is present.

87. Is flask an MVC model? If yes, justify your answer by showing an example of your application with
the help of the MVC pattern?

Basically, a flask is a minimalistic framework that behaves the same as the MVC framework. So MVC will be
perfectly suitable for the flask and we will consider the MVC pattern in the below example.

from flask import Flask


In this code your,
app = Flask(_name_)
@app.route(“/”)
Def hey():
return “Welcome to Appmajix”
app.run(debug = True)

The following code can be fragmented into

Configuration part will be,

In this code your,


app = Flask(_name_)

View part will be,

@app.route(“/”)
Def hey():
return “Welcome to Appmajix”

While your main part will be,

app.run(debug = True)

88. What are the database connections in Python Flask, explain?

Database-powered applications are supported by the flask. The relational database systems need to create a
schema that requires piping the schema.sql file into an SQLite3 command. So, in this case, you need to install
the SQLite3 command on your system to initiate and create the database in the flask.

We can request a database using flask in three ways, and they are:

 before_request(): Using this we can request database before only without passing arguments.
 after_request(): This method is called after requesting the database and also send the response to
the client.
 teardown_request(): This method is called in the cases where the responses are not guaranteed and
the exception is raised. They have no access to modify the request.

89. Explain the procedure to minimize or lower the outages of the Memcached server in your Python
development?

The following are the steps used to minimize the outages of the Memcached server in your Python
development, and they are.

 When a single instance fails, this will impact on larger load of the database server. The client makes
the request when the data is reloaded. In order to avoid this, the code that you have written must be
used to lower cache stampedes then it will be used to leave a minimal impact.
 The other way is to bring out the instance of the Memcached on a new machine by using the IP
address of the lost machine.
 Another important option is to lower the server outages is code. This code provides you with the
liberty to modify the Memcached server list with minimal work
 another way is by setting a timeout value that will be one of the options for memcac
 Class Student:
 def __init__(self, name):
 self.name = name
 S1=Student("XYZ")
print(S1.name)

 hed clients to implement the Memcached server outage. When the performance of the server goes
down, the client keeps on sending a request until the timeout limit is reached.

90. What is the Dogpile effect?

This is defined as an occurrence of an event when the cache expires and also when the websites are hit with
more requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in
the particular system the value expires then, first of all, the particular process receives the lock and begins
generating new value.

Python Coding Interview Questions

91. What are the OOP's concepts available in Python?

Ans: Python is also an object-oriented programming language like other programming languages. It also
contains different OOP's concepts, and they are

 Object
 Class
 Method
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism
Related Article: Top 50 OOPs Interview Questions

92. Define object in Python?

An object in Python is defined as an instance that has both state and behavior. Everything in Python is made
of objects.

93. What is a class in Python?

Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and
attributes.

94. How to create a class in Python?

In Python programming, the class is created using a class keyword. The syntax for creating a class is as
follows:

class ClassName:
#code (statement-suite)

Example of creating a class in Python.

Output:

XYZ

95. What is the syntax for creating an instance of a class in Python?

Ans: The syntax for creating an instance of a class is as follows:

<object-name> = <class-name>(<arguments>)

96. Define what is “Method” in Python programming?

The Method is defined as the function associated with a particular object. The method which we define should
not be unique as a class instance. Any type of object can have methods.

97. Does multiple inheritances are supported in Python?

Multiple inheritances are supported in python. It is a process that provides flexibility to inherit multiple base
classes in a child class.

An example of multiple inheritances in Python is as follows:

class Calculus:
def Sum(self,a,b):
return a+b;
class Calculus1:
def Mul(self,a,b):
return a*b;
class Derived(Calculus,Calculus1):
def Div(self,a,b):
return a/b;
d = Derived()
print(d.Sum(10,30))
print(d.Mul(10,30))
print(d.Div(10,30))

Output:

40
300
0.3333

98. What is data abstraction in Python?

In simple words, abstraction can be defined as hiding unnecessary data and showing or executing necessary
data. In technical terms, abstraction can be defined as hiding internal processes and showing only the
functionality. In Python abstraction can be achieved using encapsulation.

99. Define encapsulation in Python?

Encapsulation is one of the most important aspects of object-oriented programming. The binding or wrapping
of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to
restrict access to methods and variables.

100. What is polymorphism in Python?

By using polymorphism in Python we will understand how to perform a single task in different ways. For
example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle,
and so on.

101. Does Python make use of access specifiers?

Python does not make use of access specifiers and also it does not provide a way to access an instance
variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a
double or single underscore to act like the behavior of private and protected access specifiers.

102. How can we create an empty class in Python?

Empty class in Python is defined as a class that does not contain any code defined within the block. It can be
created using pass keywords and object to this class can be created outside the class itself.

Example:
class x:
&nbsp; pass
obj=x()
obj.id="123"
print("Id = ",obj.id)

Output:

123

103. Define Constructor in Python?

Constructor is a special type of method with a block of code to initialize the state of instance members of the
class. A constructor is called only when the instance of the object is created. It is also used to verify that they
are sufficient resources for objects to perform a specific task.

There are two types of constructors in Python, and they are:

 Parameterized constructor
 Non-parameterized constructor

104. How can we create a constructor in Python programming?

The _init_ method in Python stimulates the constructor of the class. Creating a constructor in Python can be
explained clearly in the below example.

class Student:
def __init__(self,name,id):
self.id = id;
self.name = name;
def display (self):
print("ID: %d nName: %s"%(self.id,self.name))
stu1 =Student("nirvi",105)
stu2 = Student("tanvi",106)
#accessing display() method to print employee 1 information
stu1.display();
#accessing display() method to print employee 2 information
stu2.display();

Output:

ID: 1
Name: nirvi
ID: 106
Name: Tanvi

105. Define Inheritance in Python?

When an object of child class has the ability to acquire the properties of a parent class then it is called
inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.

You might also like