Python_Question_bank_with_answers.
Python_Question_bank_with_answers.
Module 1
1. List and explain math operators used in python with example.
-----
Precedence:
The ** operator is evaluated first;
The *, /, //, and % operators are evaluated next, from left to right;
The + and - operators are evaluated last (also from left to right).
Parentheses is used to override the usual precedence if needed.
Ex: (5 - 1) * ((7 + 1) / (3 - 1))
4 * ((7 + 1) / (3 - 1))
4 * ( 8 ) / (3 - 1))
4*(8)/(2)
4 * 4.0
16.0
3. Write a python program and explain the following functions: int(), str(), float(), print(), len()
and input().
----- print('Hello world!')
print('What is your name?')
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
5. With Python programming examples to each, explain the syntax and control flow diagrams
of break and continue statements.
----- break
If the execution reaches a break statement, it immediately exits the while loop’s clause. In code, a
break statement simply contains the break keyword.
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
Continue
Continue statements are used inside loops. When the program execution reaches a continue statement,
execution immediately jumps back to the start of the loop and continues the loop’s condition.
-----(i).Before using functions in a module, we must import themodule with an import statement. In
code:
i). The import keyword
ii). The name of the module
Eg: import random
for i in range(5):
print(random.randint(1, 10))
(ii).An alternative form of the import statement is composed of the from keyword, followed by the
module name, the import keyword, and a star; for example, from random import *.
8. Explain looping control statements in Python with a syntax and example to each.
-----(i)while Loop:
The code in a while clause will be executed as long as the while statement’s condition is True.
The condition is always checked at the start of each iteration. If the condition is False, the while
clause is skipped.
Ex: defevenOdd( x ):
if (x %2==0):
print("even")
else:
print("odd")
x=int(input(“Enter the number”))
evenOdd(x)
10. Develop a Python program to generate Fibonacci sequence of length (N). Read N from the
console.
----- def fib(nterms):
n1, n2 = 0, 1
count = 0
if nterms<= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence for number "+str(nterms)+" is")
while count <nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
number = int(input("How many terms? "))
fib(number)
Output:
How many terms? 5
Fibonacci sequence for number 5 is
0
1
1
2
3
O/P:
bacon local
spam local
bacon local
global
Global Scope
Variables that are assigned outside all functions are said to exist in the global scope.
Avariable that exists in the global scope is called a global variable.
There is only one global scope, and it is created when your program begins. When your
program
terminates, the global scope is destroyed, and all its variables are forgotten.
Code in the global scope cannot use any local variables.
Ex: def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
13. Define exception handling. How exception handling is done in python with program to solve
divide by zero exception.
----- Exception Handling is a process of detecting errors and handling them. If any error occurs in
program we don’t want our program to crash instead the program must detect errors, handle them, and
continue to run.
Errors can be handled with try and except statements. The code is put in a try clause . The
program execution moves to the start of an except clause if an error happens.
14. What are functions? Explain python functions with parameters and return value.
----- A function is like a mini-program within a program. A major purpose of functions is to group
code that gets executed multiple times.
A parameteris a variable that an argument is stored in when a function is called. One special thing to
note about parameters is that the value stored in a parameter is forgotten when the function returns.
15. Develop a program to read the name and year of birth of a person. Display weather
person is senior citizen or not?
----- Name=input("Enter your name")
Year_of_Birth=int(input("Enter your year of birth"))
Current_year=2023
age=Current_year-Year_of_Birth
if age>=60:
print('senior citizen')
else:
print('not a senior citizen')
16. List and explain with example different cornparison and Boolean operators.
----- Comparison operators compare two values and evaluate down to a single Boolean value.
Operators Meaning Examples
== Equal to 42 == 42
True
!= Not equal to 2 != 3
True
Note: Read the sample programs which were initially executed in the lab .
Module 2
1. Explain negative indexing, slicing(), append() ,index(), insert(), sort(),remove(),reverse()
methods with respect to lists in Python.
----- (i). negative indexing: The integer value -1 refers to the last index in a list, the value -2refers to
the second-to-last index in a list, and so on.
Ex: spam = ['cat', 'bat', 'rat', 'elephant']
>>>spam[-1]
'elephant'
(ii). slicing(): A slice is typed between square brackets, like an index, but it has two integers separated
by a colon.
Ex: spam = ['cat', 'bat', 'rat', 'elephant']
>>>spam[0:4]
['cat', 'bat', 'rat', 'elephant']
(iii). append():To add new values to a list, use the append()method that adds the
argument to the end of the list.
Ex: spam = ['cat', 'dog', 'bat']
>>>spam.append('moose')
Print(spam)
['cat', 'dog', 'bat', 'moose']
(iv). index():List have an index() method where if the value exists in the list, the index of the value is
returned. If not, then Python produces a ValueError error.
Ex: spam = ['hello', 'hi', 'howdy', 'heyas']
>>>spam.index('hello')
0
(v). insert():The insert() method can insert a value at any index in the list.
The first argument to insert() is the index for the new value, and the secondargument is the new value
to be inserted.
Ex: spam = ['cat', 'dog', 'bat']
>>>spam.insert(1, 'chicken')
>>>spam
['cat', 'chicken', 'dog', 'bat']
(vi). Sort():Lists of number values or lists of strings can be sorted with the sort()
method.
Ex: spam = [2, 5, 3.14, 1, -7]
>>>spam.sort()
>>>spam
[-7, 1, 2, 3.14, 5]
(vii). remove():The remove() method is passed the value to be removed from the
list it is
called on.
Ex: spam = ['cat', 'bat', 'rat', 'elephant']
>>>spam.remove('bat')
>>>spam
['cat', 'rat', 'elephant']
(viii). reverse():The reverse keyword argument to have sort() function sort the
values in reverse order.
Ex: spam.sort(reverse=True)
>>>spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
2. Develop suitable Python programs with nested lists to explain copy.copy( ) and
copy.deepcopy( ) functions.
----- Python provides a module named copy that provides both the copy() and
deepcopy() functions.
(i). Copy(): copy.copy(), can be usedto make a duplicate copy of a mutable
value like a list or dictionary, not just acopy of a reference.
Ex: import copy
>>>spam = ['A', 'B', 'C', 'D']
>>>cheese = copy.copy(spam)
>>>cheese[1] = 42
>>>spam
['A', 'B', 'C', 'D']
>>>cheese
['A', 42, 'C', 'D']
(ii). Deepcopy(): If the list you need to copy contains lists, then use the
copy.deepcopy() function instead of copy.copy(). The deepcopy() function will
copy theseinner lists as well.
Ex: import copy
>>>spam = ['A', 'B', 'C', 'D']
>>>cheese = copy.deepcopy(spam)
>>>cheese[1] = 42
>>>spam
['A', 'B', 'C', 'D']
>>>cheese
['A', 42, 'C', 'D']
3. Explain different ways to delete an element from a list with suitable Python syntax and
programming examples.
----- We have two methods to delete elements in list.
(i). del(): Del method is used to delete an element from the list by giving index.
Ex: eggs = [1, 2, 3]
>>>del eggs[2]
>>>del eggs[1]
>>>del eggs[0]
(ii). remove():The remove() method is passed the value to be removed from the
list it is
called on.
Ex: spam = ['cat', 'bat', 'rat', 'elephant']
>>>spam.remove('bat')
>>>spam
['cat', 'rat', 'elephant']
Ex: d={}
for i in num:
d.setdefault(i,0)
d[i]=d[i]+1
print(d)
fori in d:
print('Frequency of '+str(i)+' is '+str(d[i]))
Output:
Enter a multidigit number: 12342312445788
{'1': 2, '2': 3, '3': 2, '4': 3, '5': 1, '7': 1, '8': 2}
Frequency of 1 is 2
Frequency of 2 is 3
Frequency of 3 is 2
Frequency of 4 is 3
Frequency of 5 is 1
Frequency of 7 is 1
Frequency of 8 is 2
7. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
-----d={}
fori in num:
d.setdefault(i,0)
d[i]=d[i]+1 print(d)
fori in d:
print('Frequency of '+str(i)+' is '+str(d[i]))
Output:
Enter a multidigit number: 12342312445788
{'1': 2, '2': 3, '3': 2, '4': 3, '5': 1, '7': 1, '8': 2}
Frequency of 1 is 2
Frequency of 2 is 3
Frequency of 3 is 2
Frequency of 4 is 3
Frequency of 5 is 1
Frequency of 7 is 1
Frequency of 8 is 2
10. Write a program to count the frequency of characters using module PrettyPrint(PPrint).
-----The pprint() and pformat() functions that will “pretty print” a dictionary’s values. This is helpful
when you want a cleaner display of the items in a dictionary than what print() provides.
Ex: import pprint
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
O/P:
{' ': 13,
',': 1,
'.': 1,
'A': 1,
'I': 1,
'a': 4,
'b': 1,
'c': 3,
'd': 3,
'e': 5,
'g': 2,
'h': 3,
'i': 6,
'k': 2,
'l': 3,
'n': 4,
'o': 2,
'p': 1,
'r': 5,
's': 3,
't': 6,
'w': 2,
'y': 1}
Items(): This method returns both key and value pair in the dictionary.
Ex: spam = {'color': 'red', 'age': 42}
for v in spam.items():
print(v)
o/p: (‘color’, ‘red’)
(‘age’, 42)
Module 3
1. Explain Python string handling methods with examples: split(),endswith(), ljust(), center(),
lstrip(),join(), startswith(),rjust(),strip(),rstrip().
----- i. join(): The join() method is useful when you have a list of strings that need to be joined
together into a single string value.
Ex: ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
ii. split(): The split() method is called on a string value and returns a list of strings.
Ex: 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
iii. endswith(),startswith():The startswith() and endswith() methods return True if the string value
they are called on begins or ends (respectively) with the string passed to the method; otherwise, they
return False.
Ex: 'Hello world!'.startswith('Hello')
True
>>> 'Hello world!'.endswith('world!')
True
iv. strip(), rstrip(), lstrip():The strip() string method will return a new string without any whitespace
characters at the beginning or end. The lstrip() and rstrip() methods will remove whitespace
characters from the left and right ends, respectively
Ex: spam = ' Hello World '
>>>spam.strip()
'Hello World'
>>>spam.lstrip()
'Hello World '
>>>spam.rstrip()
' Hello World'
v. ljust(), rjust(), center():The rjust() and ljust() string methods return a padded version of the string
they are called on, with spaces inserted to justify the text.
Ex: 'Hello World'.rjust(20)
' Hello World'
>>> 'Hello'.ljust(10)
'Hello '
The center() string method works like ljust() and rjust() but centers the text rather than justifying it to
the left or right
Ex: 'Hello'.center(20)
' Hello
2. Explain the concept of file path. Also explain absolute and relative path.
-----A file has two key properties: a filename (usually written as one word) and a path. The path
specifies the location of a file on the computer.
It has directories, folders and files.
Ex: c:\users\documents\file.txt
Absolute path: An absolute path, which always begins with the root folder. There are also the dot (.)
folders.
Calling os.path.abspath(path) will return a string of the absolute path of the argument. This is an easy
way to convert a relative path into an absolute one.
Ex: os.path.abspath('.')
'C:\\Python34'
Relative path():A relative path, which is relative to the program’s current working directory. There
are also thedot-dot (..) folders.
Calling os.path.relpath(path, start) will return a string of a relative path from the start path to path. If
start is not provided, the current working directory is used as the start path.
Ex: os.path.relpath('C:\\Windows', 'C:\\')
'Windows'
3. Explain with suitable Python program segments: (i) os.path.basename() (ii) os.path.join().
iii. os.path.dirname()
-----(i)os.path.basename(): Calling os.path.basename(path) will return a string of everything that
comes after the last slash in the path argument.
Ex:path = 'C:\\Windows\\System32\\calc.exe'
>>>os.path.basename(path)
'calc.exe'
(ii) os.path.join(): os.path.join() will return a string with a file path using the correct path separators.
Ex: import os
>>>os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
iii. os.path.dirname(): Calling os.path.dirname(path) will return a string of everything that comes
before the last slash in the path argument.
Ex:>>>os.path.dirname(path)
'C:\\Windows\\System32'
4. Explain reading and saving python program variables using shelve module with suitable
Python program.
-----You can save variables in your Python programs to binary shelf files using the shelve module.
The shelve module will let you add Save and Open features to your program.
To read and write data using the shelve module, you first import shelve. Call shelve.open() and pass it
a filename, and then store the returned shelf value in a variable.
Ex: import shelve
>>>shelfFile = shelve.open('mydata')
>>>cats = ['Zophie', 'Pooka', 'Simon']
>>>shelfFile['cats'] = cats
>>>shelfFile.close()
5. Develop a Python program to read and print the contents of a text file.
----- list1=[]
file=open("D:\\hello1.txt")
var=file.readlines()
print(var)
for i in var:
list1.append(i.strip())
print(list1)
list1.sort()
print(list1)
file.close()
file1=open("D:\\hello2.txt",'w')
for i in list1:
file1.write(i+'\n')
file1.close()
Output:
['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
Hello1.txt:['vidya', 'anugna', 'shruthi', 'bindu']
Hello2.txt:['anugna', 'bindu', 'shruthi', 'vidya'
6. Develop a Python program find the total size of all the files in the given.
-----Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.
Program:
totalSize = 0
for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
print(totalSize)
7. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file.
----- list1=[]
file=open("D:\\hello1.txt")
var=file.readlines()
print(var)
for i in var:
list1.append(i.strip())
print(list1)
list1.sort()
print(list1)
file.close()
file1=open("D:\\hello2.txt",'w')
for i in list1:
file1.write(i+'\n')
file1.close()
Output:
['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
Hello1.txt:['vidya', 'anugna', 'shruthi', 'bindu']
Hello2.txt:['anugna', 'bindu', 'shruthi', 'vidya']
10. Develop a python code to determine whether give string is a palindrome or not.
-----def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
Module 4
1. Explain permanent delete and safe delete with a suitable Python programming example to
each.
----- Permanently Deleting Files:
To delete a folder and all of its contents, you use the shutil module.
• Calling os.unlink(path) will delete the file at path.
• Calling os.rmdir(path) will delete the folder at path. This folder must be
empty of any files or folders.
• Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will
also be deleted.
Ex: import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
Safe Deletes with the send2trash Module:
A much better way to delete files and folders is send2trash module.
send2trash will send folders and files to your computer’s trash or recycle bin instead of permanently
deleting them.
Ex: import send2trash
>>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')
Output:
Creating PES_1.zip...
Adding files in C:\Users\PC\AppData\Local\Programs\Python\Python311\PES...
Adding files in C:\Users\PC\AppData\Local\Programs\Python\Python311\PES\pes1...
Done.
4. Develop a program with function named Divexp which takes two parameters a,b and c.
Write assertion foe a>0 and raise exception for b=0.
----- def DivExp(a,b):
assert a>0,"a is greater than zero"
if b==0:
raise Exception("value of b cannot be zero")
else:
c=a/b
return c
a=int(input("enter the value of A"))
b=int(input("enter the value of B"))
try:
print(DivExp(a,b))
except Exception as err:
print(err)
Output:
enter the value of A4
enter the value of B0
value of b cannot be zero
5. Explain the functions with examples: (i) shutil.copytree(), (ii). shutil.copy, (iii) shutil.move()
(iv) shutil.rmtree().
----- The shutil module provides functions for copying files, as well as entire
folders.
(i). shutil.copy(): Calling shutil.copy(source, destination) will copy the file at the path
source to the folder at the path destination.
Ex: shutil.copy('C:\\spam.txt', 'C:\\delicious')
'C:\\delicious\\spam.txt'
6. Develop a Python program to traverse the current directory by listing subfolders and files.
----- The os.walk() function is passed a single string value: the path of a folder.
import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print('')
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n))
total = 1
for i in range(n + 1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
logging.debug('End of program')
(i). Go: Clicking the Go button will cause the program to execute normally until it
terminates or reaches a breakpoint.
(ii). Step: Clicking the Step button will cause the debugger to execute the next line of
code and then pause again. The Debug Control window’s list of global and local variables
will be updated if their values change. If the next line of code is a function call, the
debugger will “step into” that function and jump to the first line of code of that function.
(iii). Over Clicking the Over button will execute the next line of code. The function’s
code will be
executed at full speed, and the debugger will pause as soon as the function call returns.
(iv). Out: Clicking the Out button will cause the debugger to execute lines of code at full
speed until it returns from the current function.
(v). Quit: If you want to stop debugging entirely and not bother to continue executing
the rest of the program, click the Quit button. The Quit button will immediately
terminate the program.
Module 5
1. Explain the methods __init__ and __str__ with suitable code example to each.
----- __init__ :
The init method (short for “initialization”) is a special method that gets invoked when an object is
instantiated. Its full name is __init__ (two underscore characters, followed by init, and then two more
underscores). An init method for the Time class might look like this:
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
2. Explain the program development concept ‘prototype and patch’ with suitable example.
----- For each function, a prototype is written that performes the basic calculation and then tested it,
patching errors along the way. This is called prototype and patch.
Ex: Here is a function that converts Times to integers:
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
And here is a function that converts an integer to a Time
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
3. Define a function which takes TWO objects representing complex numbers and returns new
complex number with a addition of two complex numbers. Define a suitable class ‘Complex’
to represent the complex number. Develop a program to read N (N >=2) complex numbers
and to compute the addition of N complex numbers
----- class Complex:
def sum(a,b):
c=Complex()
c.real=a.real+b.real
c.img=a.img+b.img
return c
a=Complex()
a.real=int(input('Enter the real part of a: '))
a.img=int(input('Enter the img part of a: '))
b=Complex()
b.real=int(input('Enter the real part of b: '))
b.img=int(input('Enter the img part of b: '))
c=complex.sum(a,b)
print(c.real,'+',c.img,'j')
Output:
Enter the real part of a:2
Enter the img part of a:3
Enter the real part of b:4
Enter the img part of b:5
6+9j
4. Explain the following with syntax and suitable code snippet: i) Class definition ii)
instantiation iii) passing an instance (or objects) as an argument iv) instances as return
values.
----- i) Class definition: A class is a programmer-defined which acts as a blue print or a prototype.
A class definition looks like this:
class Point:
"""Represents a point in 2-D space."""
The header indicates that the new class is called Point. The body is a docstring that explains
what the class is for.
ii) instantiation: Creating a new object is called instantiation, and the object is an instance of the
class. When instance is printed, Python tells you what class it belongs to and where it is stored
in memory.
Ex: blank = Point()
>>> blank
iii) instances as return values: Functions can return instances. For example, find_center takes a
Rectangle as an argument and returns a Point that contains the coordinates of the center of the
Rectangle:
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p
iv). passing an instance (or objects) as an argument:
You can pass an instance as an argument in the usual way. For example:
def print_point(p):
print('(%g, %g)' % (p.x, p.y))
print_point takes a point as an argument and displays it in mathematical notation. To invoke it, you
can pass blank as an argument:
>>> print_point(blank)
(3.0, 4.0)
5. Define pure function and modifier. Explain the role of pure functions and modifiers in
application development with suitable python programs.
----- Pure functions:
pure function because it does not modify any of the objects passed to it as arguments and it
has no effect, like displaying a value or getting user input, other than returning a value.
Ex: def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
return sum
Modifiers:
Sometimes it is useful for a function to modify the objects it gets as parameters. In that case,
the changes are visible to the caller. Functions that work this way are called modifiers.
Ex: def increment(time, seconds):
time.second += seconds
if time.second >= 60:
time.second -= 60
time.minute += 1
if time.minute >= 60:
time.minute -= 60
time.hour += 1
6. Define class and object, construct class called rectangle and initialize it with
height=100,width=200.Write a program to display the center of a rectangle.
----- A class is a programmer-defined which acts as a blue print or a prototype.
Creating a new object is called instantiation, and the object is an instance of the class.
class Rectangle:
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
7. Develop a program that uses class Student which prompts the user to enter marks in three
subjects and calculates total marks, percentage and displays the score card details.
----- class Student:
def __init__(self):
self.name=input('Enter the student name: ')
self.usn=input('Enter the student USN: ')
self.marks =[]
def getMarks(self):
total = 0
for i in range(3):
self.marks.append(int(input('Enter the marks of subject '+str(i+1)+': ')))
total+=self.marks[i]
self.marks.append(total)
def Display(self):
print('------------**********-------------',end='\n\n')
print('Student\'s score card: ')
print('Student name:', self.name)
print('Student USN:', self.usn)
for i in range(3):
print('subject '+str(i+1)+' marks:',self.marks[i])
print ('Total marks: ',self.marks[3])
print ('Percentage: ',self.marks[3]/3)
s=Student()
s.getMarks()
s.Display()
Output:
Enter the student name: Sahana
Enter the student USN: 054
Enter the marks of subject 1: 78
Enter the marks of subject 2: 67
Enter the marks of subject 3: 57