Top 50+ Python Interview Questions (2022) - Javatpoint
Top 50+ Python Interview Questions (2022) - Javatpoint
A list of frequently asked Python interview questions with answers for freshers
and experienced are given below.
1) What is Python?
Software development.
Mathematics.
System scripting.
2) Why Python?
Python allows a developer to write programs with fewer lines than some
other programming languages.
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.
Python is used in various software domains some application areas are given
below.
Games
Language development
Operating systems
⇧ SCROLL TO TOP
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.
Ad
⇧ SCROLL TO TOP
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.
It is Extensible
Object-oriented
Built-in data structure: Tuple, List, and Dictionary are useful integrated data
structures provided by the language.
Readability
High-Level Language
Cross-platform
Portable: Python programs can run on cross platforms without affecting its
performance.
⇧ SCROLL TO TOP
5) What is PEP 8?
String Literals
String literals are formed by enclosing text in the single or double quotes. For
example, string literals are string values.
Example:
# in single quotes
single = 'JavaTpoint'
# in double quotes
double = "JavaTpoint"
# multi-line String
multi = '''''Java
T
⇧ SCROLL TO TOP
point'''
print(single)
print(double)
print(multi)
Output:
JavaTpoint
JavaTpoint
Java
T
point
Numeric Literals
Python supports three types of numeric literals integer, float and complex.
Example:
# Integer literal
a = 10
#Float Literal
b = 12.3
#Complex Literal
x = 3.14j
print(a)
print(b)
print(x)
Output:
10
12.3
3.14j
Boolean Literals
Boolean literals are used to denote Boolean values. It contains either True or
False.
⇧ SCROLL TO TOP
#1 Online Counseling Website
Book Your Counseling Session with Top Experts & Grow!
BetterLYF Open
Example:
p = (1 == True)
q = (1 == False)
r = True + 3
s = False + 7
print("p is", p)
print("q is", q)
print("r:", r)
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:
word = None
print(word)
Output:
None
Built-In Functions: copy(), len(), count() are the some built-in functions.
def function_name(parameters list):
#--- statements---
return a_value
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
zip(iterator1, iterator2, iterator3 ...)
Parameters
iterator1, iterator2, iterator3: These are iterator objects that are joined together.
Return
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.
Pass by references
⇧ SCROLL TO TOP
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.
Example:
class student:
def __init__(self, name):
self.name = name
def __init__(self, name, email):
self.name = name
self.email = email
# This line will generate an error
#st = student("rahul")
# This line will call the second constructor
st = student("rahul", "rahul@gmail.com")
⇧ SCROLL TO TOP
print("Name: ", st.name)
print("Email id: ", st.email)
Output:
Name: rahul
The user can use the remove() function to delete a specific object in the list.
Example:
list_1 = [ 3, 5, 7, 3, 9, 3 ]
print(list_1)
list_1.remove(3)
print("After removal: ", list_1)
Output:
[3, 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:
list_1 = [ 3, 5, 7, 3, 9, 3 ]
print(list_1)
del list_1[2]
print("After deleting: ", list_1)
Output:
⇧ SCROLL TO TOP
[3, 5, 7, 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.
Example:
string = "IT IS IN LOWERCASE."
print(string.swapcase())
string = "it is in uppercase."
print(string.swapcase())
Output:
it is in lowercase.
IT IS IN UPPERCASE.
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:
string = " javatpoint "
string2 = " javatpoint "
string3 = " javatpoint"
print(string)
print(string2)
print(string3)
⇧ SCROLL TO TOP
print("After stripping all have placed in a sequence:")
print(string.strip())
print(string2.strip())
print(string3.strip())
Output:
javatpoint
javatpoint
javatpoint
Javatpoint
javatpoint
javatpoint
Example:
string = " javatpoint "
string2 = " javatpoint "
print(string)
print(string2)
print("After stripping all leading whitespaces:")
print(string.lstrip())
print(string2.lstrip())
Output:
javatpoint
javatpoint
javatpoint
javatpoint
After stripping, all the whitespaces are removed, and now the string looks like
the below:
⇧ SCROLL TO TOP
15) Why do we use join() function in Python?
Example:
str = "Rohan"
str2 = "ab"
# Calling function
str2 = str.join(str2)
# Displaying result
print(str2)
Output:
aRohanb
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:
# import the random module
import random
# declare a list
sample_list1 = ['Z', 'Y', 'X', 'W', 'V', 'U']
print("Original LIST1: ")
print(sample_list1)
# first shuffle
random.shuffle(sample_list1)
print("\nAfter the first shuffle of LIST1: ")
print(sample_list1)
# second shuffle
random.shuffle(sample_list1)
print("\nAfter the second shuffle of LIST1: ")
print(sample_list1)
Output:
Original LIST1:
⇧ ['Z',
SCROLL'Y',
TO TOP
'X', 'W', 'V', 'U']
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:
list_1 = ['X', 'Y', 'Z']
list_2 = [11, 22, 33]
for i in list_1:
for j in list_2:
print(i, j)
if i == 'Y' and j == 33:
print('BREAK')
break
else:
continue
break
Output:
X 11
X 22
X 33
Y 11
Y 22
Y 33
BREAK
⇧ SCROLL TO TOP
Python Break statement flowchart.
Example:
# Declaring tuple
tup = (2,4,6,8)
# Displaying value
print(tup)
# Displaying Single value
print(tup[2])
Output:
(2, 4, 6, 8)
⇧ 6
SCROLL TO TOP
It is immutable. So updating tuple will lead to an error.
Example:
# Declaring tuple
tup = (2,4,6,8)
# Displaying value
print(tup)
# Displaying Single value
print(tup[2])
# Updating by assigning new value
tup[2]=22
# Displaying Single value
print(tup[2])
Output:
tup[2]=22
(2, 4, 6, 8)
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.
⇧ SCROLL TO TOP
Here, os and os.path - modules include a function for accessing the filesystem
while shutil - module enables you to copy and delete the files.
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.
Read-only mode (r): Open a file for reading. It is the default mode.
Write-only mode (w): Open a file for writing. If the file contains data, data
would be lost. Other a new file is created.
Read-Write mode (rw): Open a file for reading, write mode. It means
updating mode.
Append mode (a): Open for writing, append to the end of the file, if the file
exists.
Example:
# Unary Operator
A = 12
B = -(A)
print (B)
⇧ SCROLL TO TOP
# Binary Operator
A = 12
B = 13
print (A + B)
print (B * A)
#Ternary Operator
A = 12
B = 13
min = A if A < B else B
print(min)
Output:
# Unary Operator
-12
# Binary Operator
25
156
# Ternary Operator
12
Assignment Operators
Logical Operators
Membership Operators
Identity Operators
Bitwise Operators
⇧ SCROLL TO TOP
Arithmetic operators perform basic arithmetic operations. For example "+" is
used to add and "?" is used for subtraction.
Example:
# Adding two values
print(12+23)
# Subtracting two values
print(12-23)
# Multiplying two values
print(12*23)
# Dividing two values
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.
⇧#SCROLL TOofTOP
Examples Relational Operators
Example:
a, b = 10, 12
print(a==b) # False
print(a<b) # True
print(a<=b) # True
print(a!=b) # True
Output:
False
True
True
True
Assignment operators are used to assigning values to the variables. See the
examples below.
Example:
# Examples of Assignment operators
a=12
print(a) # 12
a += 2
print(a) # 14
a -= 2
print(a) # 12
a *=2
print(a) # 24
a **=2
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:
# Logical operator examples
⇧ SCROLL TO TOP
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not b) # True
Output:
False
True
True
Example:
# Membership operators examples
list = [2,4,6,7,3,4]
print(5 in list) # False
cities = ("india","delhi")
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:
# Identity operator example
a = 10
b = 12
print(a is b) # False
print(a is not b) # True
Output:
False
True
Bitwise Operators are used to performing operations over the bits. The binary
⇧operators
SCROLL TO(&, TOP
|, OR) work on bits. See the example below.
Example:
# Identity operator example
a = 10
b = 12
print(a & b) # 8
print(a | b) # 14
print(a ^ b) # 6
print(~a) # -11
Output:
14
-11
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:
unicode_1 = ("\u0123", "\u2665", "\U0001f638", "\u265E", "\u265F", "\u2168")
print (unicode_1)
Output:
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.
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:
def function_is_called():
def function_is_returned():
print("JavaTpoint")
return function_is_returned
new_1 = function_is_called()
# Outputs "JavaTpoint"
new_1()
Output:
JavaTpoint
27) What are the rules for a local and global variable in
Python?
Global Variables:
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.
⇧ SCROLL TO TOP
Global variables are accessible anywhere in the program, and any function
can access and modify its value.
Example:
A = "JavaTpoint"
def my_function():
print(A)
my_function()
Output:
JavaTpoint
Local Variables:
Example:
def my_function2():
K = "JavaTpoint Local"
print(K)
my_function2()
Output:
JavaTpoint Local
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.
⇧29) What
SCROLL TOare
TOPiterators 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.
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:
Q = "JavaTpoint, Python Interview Questions!"
print(Q[2:25])
Output:
The following example contains some keys Country Hero & Cartoon. Their
corresponding values are India, Modi, and Rahul respectively.
dict = {'Country': 'India', 'Hero': 'Modi', 'Cartoon': 'Rahul'}
print ("Country: ", dict['Country'])
print ("Hero: ", dict['Hero'])
print ("Cartoon: ", dict['Cartoon'])
Output:
Country: India
Hero: Modi
Cartoon: Rahul
Example:
class Student:
pass # Passing class
class Student:
def info():
pass # Passing function
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".
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:
SCROLL TO TOP
# One-line docstrings
def hello():
"""A function to greet."""
return "hello"
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.
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.
Help() and dir() both functions are accessible from the Python interpreter and
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").
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.
The shortest way to open a text file is by using "with" command in the following
manner:
Example:
with open("FILE NAME", "r") as fp:
fileData = fp.read()
# To print the contents of the file
print(fileData)
Output:
⇧42) What
SCROLL TOis the
TOP 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:
list_1 = ["A","B","C"]
s_1 = "Javatpoint"
# creating enumerate objects
object_1 = enumerate(list_1)
object_2 = enumerate(s_1)
print ("Return type:",type(object_1))
print (list(enumerate(list_1)))
print (list(enumerate(s_1)))
Output:
Return type:
[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7, 'i'), (8, 'n'), (9, 't')]
Since indexing starts from zero, an element present at 3rd index is 7. So, the
output is 7.
Type conversion refers to the conversion of one data type iinto another.
list() - This function is used to convert any data type to a list type.
⇧str()
SCROLL TOtoTOP
- Used convert integer into a string.
complex(real,imag) - This functionconverts real numbers to complex(real,imag)
number.
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.
Example:
import smtplib
# Calling SMTP
s = smtplib.SMTP('smtp.gmail.com', 587)
# TLS for network security
s.starttls()
# User email Authentication
s.login("sender@email_id", "sender_email_id_password")
# Message to be sent
message = "Message_sender_need_to_send"
# Sending the mail
s.sendmail("sender@email_id ", "receiver@email_id", message)
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:
import array as arr
User_Array = arr.array('i', [1,2,3,4])
User_list = [1, 'abc', 1.20]
print (User_Array)
print (User_list)
Output:
⇧47) What
SCROLL TOis lambda
TOP 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.
Lambda forms in Python does not have the statement because it is used to
make the new function object and return them in runtime.
Example:
def New_func():
print ("Hi, Welcome to JavaTpoint")
New_func() #calling the function
Output:
Example:
class Employee_1:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E_1 = Employee_1("pqr", 20, 25000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E_1.name)
print(E_1.age)
print(E_1.salary)
⇧Output:
SCROLL TO TOP
pqr
20
25000
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.
import random
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
The Random class that is used and instantiated creates independent multiple
random number generators.
⇧interpreter
SCROLL TO uses
TOPit 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.
os
sys
math
random
data time
JSON
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.
NumPy is not just more efficient; it is also more convenient. We get a lot
⇧ SCROLL TO TOP
of vector and matrix operations for free, which sometimes allow one to
avoid unnecessary work. And they are also efficiently implemented.
NumPy array is faster and we get a lot built in with NumPy, FFTs,
convolutions, fast searching, basic statistics, linear algebra, histograms,
etc.
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.
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.
Options:
a. Only Statement 1
b. Statement 1 and 2
c. Statement 1 and 3
Hide Answer
Workspace
Options:
Hide Answer
Workspace
Options:
a. Only Statement 3
b. Statement 1 and 3
c. Statement 2 and 3
d. Only Statement 2
Hide Answer
Workspace
Statement 2: Python namespaces are classified into three types - local, global
and built-in.
Options:
a. Only Statement 1
b. Only Statement 3
c. Statement 1 and 2
d. Statement 1 and 3
Hide Answer
Workspace
Hide 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 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
Hide Answer
Workspace
Code:
⇧ SCROLL TO TOP
# assigning a variable
myint = 10
# defining a function
def myfunction():
# reassigning a variable
myint = 20
# calling the function
myfunction()
# printing the value of the variable
print(myint)
Options:
a. 10
b. 20
c. 0
d. Traceback Error
Hide Answer
Workspace
Answer: A: 10
Explanation: 10 is printed.
Code:
# assigning a variable
myint = 21
# using if False statement
if False:
# reassigning a variable
myint = 34
# defining a function
def myfunction():
if True:
⇧ SCROLL TO TOP
# reassigning a variable
myint = 65
# calling the function
myfunction()
# printing the value of the variable
print(myint)
Options:
a. 65
b. Traceback Error
c. 21
d. 34
Hide Answer
Workspace
Answer: C: 21
Explanation: 21 is printed.
9) Among the following statements based on the difference between lists and tuples,
which one statement is TRUE?
Options:
a. Statement 1
b. Statement 4
c. Statement 2
d. Statement 3
Hide Answer
Workspace
⇧ SCROLL TO TOP
Answer: B: Statement 4
Code:
# defining a list
my_list = [7, 9, 8, 2, 5, 0, 1, 3, 6]
# using the pop() function
my_list.pop(2)
# printing the final list
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]
Hide Answer
Workspace
Answer: A: [7, 9, 2, 5, 0, 1, 3, 6]
Explanation: The pop() function is used to remove the element from the list.
The function's parameter is the index value, n, of the data element to be
removed from the list.
Thus, the pop(n) function removes the nth element from the list. As in the
above case, the index number is 2. Hence, the pop(2) function removes the
second element from my_list, i.e., 8.
⇧ SCROLL TO TOP