Python Interview Questions Answers
Python Interview Questions Answers
for 2023
By Steve Campbell Updated January 14, 2023
2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python
code more readable.
The allocation of Python heap space for Python objects is done by the Python memory
manager. The core API gives access to some tools for the programmer to code.
Python also has an inbuilt garbage collector, which recycles all the unused memory and
frees the memory and makes it available to the heap space.
6) What are the tools that help to find bugs or perform the static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns
about the style and complexity of the bug. Pylint is another tool that verifies whether the
module meets the coding standard.
List
Sets
Dictionaries
Immutable built-in types
Strings
Tuples
Numbers
Strings
Tuples
Numbers
The folder of Python program is a package of modules. A package can have modules or
subfolders.
26) What are the rules for local and global variables in Python?
Here are the rules for local and global variables in Python:
Local variables: If a variable is assigned a new value anywhere within the function’s body,
it’s assumed to be local.
Global variables: Those variables that are only referenced inside a function are implicitly
global.
28) Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
Script file’s mode must be executable, and the first line must begin with # (
#!/usr/local/bin/python)
import random
random.random()
Module = PyImport_ImportModule("<modulename>");
Python comprises of a huge standard library for most Internet platforms like Email,
HTML, etc.
Python does not require explicit memory management as the interpreter itself
allocates the memory to new variables and free them automatically
Provide easy readability due to use of square brackets
Easy-to-learn for beginners
Having the built-in data types saves programming time and e몭ort from declaring
variables
34) Mention the use of the split function in Python
The use of the split function in Python is that it breaks a string into shorter strings using
the defined separator. It gives a list of all words present in the string.
Flask is part of the micro-framework. Which means it will have little to no dependencies
on external libraries. It makes the framework light while there is a little dependency to
update and less security bugs.
Pyramids are built for larger applications. It provides flexibility and lets the developer use
the right tools for their project. The developer can choose the database, URL structure,
templating style, and more. Like Pyramid, Django can also be used for larger applications.
It includes an ORM.
38) Explain what is the common way for the Flask script to work?
The common way for the flask script to work is:
40) Is Flask an MVC model, and if yes give an example showing MVC
pattern for your application?
Basically, Flask is a minimalistic framework that behaves same as MVC framework. So
MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following
example
@app.route("/") @app.route("/")
app.run(debug =
While you model or main part will be
True)
app.run(debug = True)
41) Explain database connection in Python Flask?
Flask supports database-powered applications (RDBS). Such a system requires creating a
schema, which requires piping the shema.sql file into a sqlite3 command. So you need to
install sqlite3 command in order to create or initiate the database in Flask.
42) If you have multiple Memcache servers, and one of them fails that
contain data, will it try to get them?
The data in the failed server won’t get removed, but there is a provision for auto-failure,
which you can configure for multiple nodes. Fail-over can be triggered during any kind of
socket or Memcached server level errors and not during normal client errors like adding
an existing key, etc.
43) Explain how you can minimize the Memcached server outages in your
Python Development?
When one instance fails, several of them goes down, this will put a larger load on the
database server when lost data is reloaded as the client make a request. To avoid
this, if your code has been written to minimize cache stampedes, then it will leave a
minimal impact
Another way is to bring up an instance of memcached on a new machine using the
lost machine’s IP address
Code is another option to minimize server outages as it gives you the liberty to
change the Memcached server list with minimal work
Setting timeout value is another option that some Memcached clients implement for
Memcached server outage. When your Memcached server goes down, the client will
keep trying to send a request till the time-out limit is reached.
44) Explain what is Dogpile e몭ect? How can you prevent this e몭ect?
Dogpile e몭ect is referred to the event when cache expires, and websites are hit by the
multiple requests made by the client at the same time. This e몭ect can be prevented by
using a semaphore lock. In this system, when the value expires, the first process acquires
the lock and starts generating a new value.
45) Explain how memcached should not be used in your Python project?
Here are the ways you should not use memcached in your Python project:
When you want to justify one condition while the other condition is not true, then you use
Python if-else statement.
Python if Statement Syntax:
if expression
Statement
else
Statement
def main():
x,y =2,8
if __name__ == "__main__":
main()
while expression
Statement
x=0
#define a while loop
while(x <4):
print(x)
x = x+1
48) What is enumerate() in Python?
Enumerate() in Python is a built-in function used for assigning an index to each item of the
iterable object. It adds a loop on the iterable objects while keeping track of the current
item and returns the object in an enumerable form. This object can be used in a for loop
to convert it into a list by using list() method.
Suppose we want to do numbering for our month ( Jan, Feb, Marc, ….June), so we
declare the variable i that enumerate the numbers while m will print the number of
month in list.
49) How can you use for loop to repeat the same statement over and
again?
You can use for loop for even repeating the same statement over and again. Here in the
example, we have printed out the word “guru99” three times.
Example:
To repeat the same statement a number of times, we have declared the number in
variable i (i in 123). So when you run the code as shown below, it prints the statement
(guru99) that many times the number declared for our the variable in ( i in 123).
for i in '123':
print ("guru99",i,)
Syntax:
Tup = ('Jan','feb','march')
To write an empty tuple, you need to write as two parentheses containing nothing-
tup1 = ();
Example
52) How can you copy the entire dictionary to a new dictionary?
You can also copy the entire dictionary to a new dictionary. For example, here we have
copied our original dictionary to the new dictionary name “Boys” and “Girls”.
Example
Example
Example:
56) Give an example of Dictionary len() and Python List cmp() method
Dictionary len() Example:
cmp() Example:
copy()
update()
items()
items()
sort()
len()
cmp()
Str()
Example: For arithmetic operators, we will take a simple example of addition where we
will add two-digit 4+5=9
x= 4
y= 5
print(x + y)
a = True
b = False
print(('a and b is',a and b))
print(('a or b is',a or b))
print(('not a is',not a))
Example:
For example here, we check whether the value of x=4 and value of y=8 is available in list or
not by using in and not in operators.
x = 4
y = 8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print("Line 1 x is available in the given list")
else:
print("Line 1 x is not available in the given list")
if ( y not in list ):
print("Line 2 y is not available in the given list")
else:
print("Line 2 y is available in the given list")
v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;
print("Value of (v+w) * x/ y is ", z)
You can declare an array in Python while initializing it using the following syntax.
arrayName = array.array(type code for data type, [array,items])
Array Syntax
Example
The syntax is
arrayName[indexNum]
Example
import array
balance = array.array('i', [300,200,100])
print(balance[1])
The syntax is
arrayName.insert(index, value)
Example
Let us add a new value right a몭er the second item of the array. Currently, our balance
array has three items: 300, 200, and 100. Consider the second array item with a value of
200 and index 1.
In order to insert the new value right “a몭er” index 1, you need to reference index 2 in your
insert method, as shown in the below Python array example:
import array
balance = array.array('i', [300,200,100])
balance.insert(2, 150)
print(balance)
65) How can you delete elements in array?
With this operation, you can delete one item from an array by value. This method accepts
only one argument, value. A몭er running this method, the array items are re-arranged, and
indices are re-assigned.
The syntax is
arrayName.remove(value)
Example
66) How can you search and get the index of a value in an array?
With this operation, you can search for an item in an array based on its value. This method
accepts only one argument, value. It is a non-destructive method, which means it does
not a몭ect the array values.
The syntax is
arrayName.index(value)
Example
Let’s find the value of “3” in the array. This method returns the index of the searched
value.
Example:
def main():
# exercise the class methods
c = myClass ()
c.method1()
c.method2(" Testing is fun")
if __name__== "__main__":
main()
Example of inheritance:
class childClass(myClass):
#def method1(self):
#myClass.method1(self);
#print ("childClass Method1")
def method2(self):
print("childClass method2")
def main():
# exercise the class methods
c2 = childClass()
c2.method1()
#c2.method2()
if __name__== "__main__":
main()
class User:
name = ""
def sayHello(self):
print("Welcome to Guru99, " + self.name)
User1 = User("Alex")
User1.sayHello()
You can use square brackets for slicing along with the index or indices to obtain a
substring.
var1 = "Guru99!"
var2 = "Software Testing"
print ("var1[0]:",var1[0])
print ("var2[1:5]:",var2[1:5])
73) Explain all string operators with example
String operators with example:
Raw string suppresses the actual meaning of Print r’\n’ prints \n and print
r/R
escape characters. R’/n’ prints \n
import time
print("Welcome to guru99 Python Tutorials")
time.sleep(5)
print("This message will be printed after a wait of 5 seconds")
def display():
print('Welcome to Guru99 Tutorials')
t = Timer(5, display)
t.start()
import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print(str)
# The calendar can give info based on local such a names of days
and months (full and abbreviated forms)
for name in calendar.month_name:
print(name)
for day in calendar.day_name:
print(day)
# calculate days based on a rule: For instance an audit day on
the second Monday of every month
# Figure out what days that would be for each month, we can use
the script as shown here
for month in range(1, 13):
# It retrieves a list of weeks that represent the month
mycal = calendar.monthcalendar(2025, month)
# The first MONDAY has to be within the first two weeks
week1 = mycal[0]
week2 = mycal[1]
if week1[calendar.MONDAY] != 0:
auditday = week1[calendar.MONDAY]
else:
# if the first MONDAY isn't in the first week, it must be in
the second week
auditday = week2[calendar.MONDAY]
print("%10s %2d" % (calendar.month_name[month], auditday))
ZipFile.write(filename)
import os
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive
Division by Zero
Accessing a file that does not exist.
Addition of two incompatible types
Trying to access a nonexistent index of a sequence
Removing the table from the disconnected database server.
ATM withdrawal of more than the available amount
79) Explain important Python errors
The important Python errors are 1) ArithmeticError, 2) ImportError, and 3) IndexError.
Example:
import json
x = {
"name": "Ken",
"age": 45,
"married": True,
"children": ("Alice","Bob"),
"pets": ['Dog'],
"cars": [
{"model": "Audi A1", "mpg": 15.1},
{"model": "Zeep Compass", "mpg": 18.1}
]
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)
81) Explain in detail JSON to Python (Decoding) with example
JSON string decoding is done with the help of inbuilt method json.loads() &
json.load() of JSON library in Python.
Here translation table show example of JSON objects to Python objects which are helpful
to perform decoding in Python of JSON string.
JSON Python
Object Dict
Array List
String Unicode
True True
False False
Null None
The basic JSON to Python example of decoding with the help of json.loads function:
83) Write a Python code for array in numpy to create Python Matrix
Code for array in numpy to create Python Matrix
import numpy as np
M1 = np.array([[5, 10, 15], [3, 6, 9], [4, 8, 12]])
print(M1)
import numpy as np
M1 = np.array([[3, 6, 9], [5, 10, 15], [7, 14, 21]])
M2 = np.array([[9, 18, 27], [11, 22, 33], [13, 26, 39]])
M3 = M1 M2
print(M3)
[start:end]
If the start index is not given, it is considered as 0. For example [:5], it means as [0:5].
If the end is not passed, it will take as the length of the array.
If the start/end has negative values, it will the slicing will be done from the end of the
array.
Before we work on slicing on a matrix, let us first understand how to apply slice on a
simple array.
import numpy as np
arr = np.array([2,4,6,8,10,12,14,16])
print(arr[3:6]) # will print the elements from 3 to 5
print(arr[:5]) # will print the elements from 0 to 4
print(arr[2:]) # will print the elements from 2 to length of the
array.
print(arr[5:1]) # will print from the end i.e. 5 to 2
print(arr[:1]) # will print from end i.e. 0 to 2
def cal_average(num):
sum_num = 0
for t in num:
sum_num = sum_num + t
list1 = [2,3,4,3,10,3,5,6,3]
elm_count = list1.count(3)
print('The count of element: 3 is ', elm_count)
90) Write a code to get index of an element in a list using for loop
Code to get index of an element in a list using for loop:
my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
all_indexes = []
for i in range(0, len(my_list)) :
if my_list[i] == 'Guru' :
all_indexes.append(i)
print("Originallist ", my_list)
print("Indexes for element Guru : ", all_indexes)
In the Python 3 print without newline example below, we want the strings to print on the
same line in Python. To get that working, just add end=”” inside print() as shown in the
example below:
print("Hello World ", end="")
print("Welcome to Guru99 Tutorials")
93) How to print the star(*) pattern without newline and space?
Code to print the star(*) pattern without newline and space:
About
About Us
Advertise with Us
Write For Us
Contact Us
Career Suggestion
Career Suggestion
SAP Career Suggestion Tool
So몭ware Testing as a Career
Interesting
eBook
Blog
Quiz
SAP eBook
Execute online
Execute Java Online
Execute Javascript
Execute HTML
Execute Python