Python Sample Questions
Python Sample Questions
2) What is PEP 8?
Python language is an interpreted language. Python program runs directly from the
source code. It converts the source code that is written by the programmer into an
intermediate language, which is again translated into machine language that has to
be executed.
Python memory is managed by Python private heap space. All Python objects and
data structures are located in a private heap. The programmer does not have an
access to this private heap, and the interpreter takes care of this Python private
heap.
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.
The difference between list and tuple is that list is mutable while tuple is not. Tuple
can be hashed, for example., as a key for dictionaries.
Everything in Python is an object, and all variables hold references to the objects.
The reference values are according to the functions. Therefore, you cannot change
the value of the references. However, you can change the objects if it is mutable.
They are syntax constructions to ease the creation of a Dictionary or List based on
existing iterable.
• List
• Sets
• Dictionaries
• Immutable built-in types
• Strings
• Tuples
• Numbers
• Strings
• Tuples
• Numbers
A lambda form in python does not have statements as it is used to make new
function object and then return them at runtime.
In Python, iterators are used to iterate a group of elements, containers like a list.
A mechanism to select a range of items from sequence types like list, tuple, strings
etc., is known as slicing.
Python sequences can be index in positive and negative numbers. For positive
index, 0 is the first index, 1 is the second index, and so forth. For the negative
index, (-1) is the last index, and (-2) is the second last index, and so forth.
In order to convert a number into a string, use the inbuilt function str(). If you want
a octal or hexadecimal representation, use the inbuilt function oct() or hex().
Xrange returns the xrange object while range returns the list and uses the same
memory and no matter what the range size is.
In Python, module is the way to structure a program. Each Python program file is a
module, which imports other modules like objects and attributes.
26) What are the rules for local and global variables in Python?
Here are the rules for local and global variables in Python:
Global variables: Those variables that are only referenced inside a function are
implicitly global.
To share global variables across modules within a single program, create a special
module. Import the config module in all modules of your application. The module
will be available as a global variable across modules.
28) Explain how can you make a Python Script executable on Unix?
Module = PyImport_ImportModule(“<modulename>”);
It is a Floor Divisionoperator, which is used for dividing two operands with the
result as a quotient showing only digits before the decimal point. For instance,
10//5 = 2 and 10.0//5.0 = 2.0.
• 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 effort from
declaring variables
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.
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.
Flask-WTF offers simple integration with WTForms. Features include for Flask
WTF are:
38) Explain what is the common way for the Flask script to work?
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.run(debug = True)
41) Explain database connection in Python 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 effect? How can you prevent this effect?
Dogpile effect 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 effect 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:
if __name__ == "__main__":
main()
47) Explain While loop in Python with example
While loop does the exact same thing what “if statement” does, but instead of
running the code block once, they jump back to the point where it began the code
and repeat the whole process again.
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.
#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"]
for i, m in enumerate (Months):
print(i,m)
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,)
50) What is Tuple Matching in Python?
Syntax:
Tup = ('Jan','feb','march')
To write an empty tuple, you need to write as two parentheses containing nothing-
tup1 = ();
51) Explain Dictionary in Python with example
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:
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
studentX=Boys.copy()
studentY=Girls.copy()
print(studentX)
print(studentY)
53) How can you Update Python Dictionary?
Example:
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Dict.update({"Sarah":9})
print(Dict)
54) Give example of dictionary items() method
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
print("Students Name: %s" % list(Dict.items()))
55) How can you sort elements in Python dictionary?
In the dictionary, you can easily sort the elements. For example, if we want to print
the name of the elements of our dictionary alphabetically, we have to use for loop.
It will sort each element of the dictionary accordingly.
Example:
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
Students = list(Dict.keys())
Students.sort()
for S in Students:
print(":".join((S,str(Dict[S]))))
56) Give an example of Dictionary len() and Python List cmp() method
• copy()
• update()
• items()
• sort()
• len()
• cmp()
• Str()
These operators test for membership in a sequence such as lists, strings, or tuples.
Two membership operators are used in Python. (in, not in). It gives the result based
on the variable present in a specified sequence or string.
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")
61) Write code to demonstrate operator precedence in Python:
v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;
print("Value of (v+w) * x/ y is ", z)
62) Explain arrays in Pythons with example
Example:
import array as myarray
abc = myarray.array('d', [2.5, 4.9, 6.7])
63) How can you access array elements?
The syntax is
arrayName[indexNum]
Example:
import array
balance = array.array('i', [300,200,100])
print(balance[1])
64) How can you insert elements in array?
Python array insert operation enables you to insert one or more items into an array
at the beginning, end, or any given index of the array. This method expects two
arguments index and value.
The syntax is
arrayName.insert(index, value)
Example:
Let us add a new value right after 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 “after” 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. After running this method, the array items are
re-arranged, and indices are re-assigned.
The syntax is
arrayName.remove(value)
Example:
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 affect 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.
import array as myarray
number = myarray.array('b', [2, 3, 4, 5, 6])
print(number.index(3))
67) How can you reverse array in Python?
Example:
import array as myarray
number = myarray.array('b', [1,2, 3])
number.reverse()
print(number)
68) Give example to convert array to Unicode
def method2(self,someString):
print("Software Testing:" + someString)
def main():
# exercise the class methods
c = myClass ()
c.method1()
c.method2(" Testing is fun")
if __name__== "__main__":
main()
70) Explain Inheritance with example
Example of inheritance:
# Example file for working with classes
class myClass():
def method1(self):
print("Guru99")
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()
71) Give example of Python constructors
def sayHello(self):
print("Welcome to Guru99, " + self.name)
User1 = User("Alex")
User1.sayHello()
72) How can you access values in string?
Python does not support a character type, these are treated as strings of length one,
also considered as a substring.
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
Timer is a method available with Threading, and it helps to get the same
functionality as Python time sleep.
from threading import Timer
def display():
print('Welcome to Guru99 Tutorials')
t = Timer(5, display)
t.start()
76) Give example of calendar class
# 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))
77) Explain Python ZIP file with example
ZipFile.write(filename)
Example of Python ZIP file
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
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
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
number – int Number – int, long
number – real Float
True True
False False
Null None
The basic JSON to Python example of decoding with the help of json.loads
function:
import json # json library imported
# json data string
person_data = '{ "person": { "name": "Kenn", "sex": "male", "age":
28}}'
# Decoding or converting JSON format in dictionary using loads()
dict_obj = json.loads(person_data)
print(dict_obj)
# check type of dict_obj
print("Type of dict_obj", type(dict_obj))
# get human object details
print("Person......", dict_obj.get('person'))
82) Write code for encode() method
import numpy as np
M1 = np.array([[3, 6], [5, -10]])
M2 = np.array([[9, -18], [11, 22]])
M3 = M1.dot(M2)
print(M3)
86) Explain slicing of matrix with example
Slicing will return you the elements from the matrix based on the start /end index
given.
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
87) Write Python code to find average via loop
From Python 3+, there is an additional parameter introduced for print() called
end=. This parameter takes care of removing the newline that is added by default in
print().
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?