Python Question Bank With Answers. (1)
Python Question Bank With Answers. (1)
6. Explain TWO ways of importing modules into application in Python with syntax and
suitable programming examples.
-----(i).Before using functions in a module, we must import themodule with an import statement. In
code:
Continue
The import keyword
Continue statements are used inside loops. When the program execution reaches a continue statement,
The name of the module
execution immediately jumps back to the start of the loop and continues the loop’s condition.
Optionally, more module names, as long as they are separated bycommas.
Eg: import random
Eg: while True:
fori in range(5):
print('Who are you?')
print(random.randint(1, 10))
name = input()
if name != 'Joe':
(ii).An alternative form of the import statement is composed of the from keyword, followed by
continue
themodule name, the import keyword, and a star; for example, from random import *.
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
7. Write a function to calculate factorial of a number. Develop a program to compute
password == 'swordfish':
break binomialcoefficient (Given N and R).
print('Access granted.')
----- def factorial(z):
if z==1:
return 1
else:
return z* factorial(z-1)
defbinomial_coefficient(n,k):
a= (factorial(n) / factorial(k) * factorial(n-k))
return a
n=int(input("enter a number to find factorial"))
print("The factorial of number "+str(n) +"is",factorial(n))
k=int(input("enter the number to find binomial coefficient"))
print("The binomial coefficient is:",binomial_coefficient(n,k))
Output
enter a number to find factorial4
The factorial of number 4is 24
enter the number to find binomial coefficient2
The binomial coefficient is: 6.0
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")
(ii) for Loops and the range() Function: else:
for loop statement and the range() function is used to execute a block of code only a certain number print("odd")
of times In code, a for includes the following:
x=int(input(“Enter the number”))
The for keyword
A variable name evenOdd(x)
The in keyword
A call to the range() method with up to three integers passed to it 10. Develop a Python program to generate Fibonacci sequence of length (N). Read N from the
A colon console.
Starting on the next line, an indented block of code (called the forclause) ----- def fib(nterms):
n1, n2 = 0, 1
Example: print('My name is') count = 0
fori in range(5): ifnterms<= 0:
print('Jimmy Five Times (' + str(i) + ')') print("Please enter a positive integer")
else: eggs = 'spam local'
print("Fibonacci sequence for number "+str(nterms)+" is") print(eggs) # prints 'spam local'
while count <nterms: def bacon():
print(n1) eggs = 'bacon local'
nth = n1 + n2 print(eggs) # prints 'bacon local'
n1 = n2 spam()
n2 = nth print(eggs) # prints 'bacon local'
count += 1 eggs = 'global'
number = int(input("How many terms? ")) bacon()
fib(number) print(eggs) # prints 'global'
Output:
How many terms? 5 O/P:
Fibonacci sequence for number 5 is bacon local
0 spam local
1 bacon local
1 global
2
3 12. Explain local and global scope in python.
----- Local Scope
11. Explain FOUR scope rules of variables in Python. A local scope is created whenever a function is called.
-----1. Local Variables Cannot Be Used in the Global Scope. Parameters and variables that are assigned in function call termed as function’slocal scope.
When the program execution is in the global scope, no local scopes exist. This is why only global A variable that exists in a local scope is called a local variable.
variables can be used in the global scope Any variables assigned in this function exist within the local scope.
Ex: def spam(): When the function returns, the local scope is destroyed, and these variables are forgotten.
eggs = 31337 A local scope can access global variables.
spam() Ex: def spam():
print(eggs) eggs = 99
The error happens because the eggs variable exists only in the local scope created when spam() is bacon()
called. Once the program execution returns from spam, that local scope is destroyed, and there is no print(eggs)
longer a variable named eggs.
Global Scope
2. Local Scopes Cannot Use Variables in Other Local Scopes. Variables that are assigned outside all functions are said to exist in the global scope.
The local variables in one function are completely separate from the local variables in another
Avariable that exists in the global scope is called a global variable.
function.
There is only one global scope, and it is created when your program begins. When your
Ex:def spam():
program
eggs = 99
bacon() terminates, the global scope is destroyed, and all its variables are forgotten.
print(eggs) Code in the global scope cannot use any local variables.
def bacon(): Ex: def spam():
ham = 101 print(eggs)
eggs = 0 eggs = 42
spam() spam()
print(eggs)
3. Global Variables Can Be Read from a Local Scope
def spam(): 13. Define exception handling. How exception handling is done in python with program to solve
print(eggs) divide by zero exception.
eggs = 42 ----- Exception Handling is a process of detecting errors and handling them. If any error occurs in
spam() program we don’t want our program to crash instead the program must detect errors, handle them, and
print(eggs) continue to run.
Since there is no parameter named eggs or any code that assigns eggs a value in the spam() function, Errors can be handled with try and except statements. The code is put in a try clause . The
when eggs is used in spam(), Python considers it a reference to the global variable eggs. This is why program execution moves to the start of an except clause if an error happens.
42 is printed when the
previous program is run. Program: divide by zero exception.
def spam(divideBy):
4. Local and Global Variables with the Same Name try:
Avoid using local variables that have the same name as a global variable or another local variable. return 42 / divideBy
def spam(): exceptZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2)) Print(spam)
print(spam(12)) ['cat', 'dog', 'bat', 'moose']
print(spam(0))
print(spam(1)) (iv). index():List have an index() method where if the value exists in the list, the index of the value is
O/P returned. If not, then Python produces a ValueError error.
21.0 Ex: spam = ['hello', 'hi', 'howdy', 'heyas']
3.5 >>>spam.index('hello')
Error: Invalid argument.
0
None
42.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
14. What are functions? Explain python functions with parameters and return value. to be inserted.
----- A function is like a mini-program within a program. A major purpose of functions is to group Ex: spam = ['cat', 'dog', 'bat']
code that gets executed multiple times. >>>spam.insert(1, 'chicken')
A parameteris a variable that an argument is stored in when a function is called. One special thing to >>>spam
note about parameters is that the value stored in a parameter is forgotten when the function returns. ['cat', 'chicken', 'dog', 'bat']
Ex: def hello(name): (vi). Sort():Lists of number values or lists of strings can be sorted with the sort()
print('Hello ' + name) method.
hello('Alice') Ex: spam = [2, 5, 3.14, 1, -7]
hello('Bob') >>>spam.sort()
Return Values and return Statements. >>>spam
The value that a function call evaluates to is called the return valueof the function. [-7, 1, 2, 3.14, 5]
We can specify return value with a return statement. A return statement consists of the following:
The return keyword (vii). remove():The remove() method is passed the value to be removed from the list it is
The value or expression that the function should return. called on.
Ex: import random Ex: spam = ['cat', 'bat', 'rat', 'elephant']
defgetAnswer(answerNumber): >>>spam.remove('bat')
ifanswerNumber == 1:
>>>spam
return 'It is certain'
['cat', 'rat', 'elephant']
Note: Read the sample programs which were initially executed in the lab .
(viii). reverse():The reverse keyword argument to have sort() function sort the values in reverse
order.
Ex: spam.sort(reverse=True)
Module 2 >>>spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
1. Explain negative indexing, slicing(), append() ,index(), insert(), sort(),remove(),reverse() 2. Develop suitable Python programs with nested lists to explain copy.copy( ) and
methods with respect to lists in Python. copy.deepcopy( ) functions.
----- (i). negative indexing: The integer value -1 refers to the last index in a list, the value -2refers to ----- Python provides a module named copy that provides both the copy() and deepcopy() functions.
the second-to-last index in a list, and so on. (i). Copy(): copy.copy(), can be usedto make a duplicate copy of a mutable value like a list or
Ex: spam = ['cat', 'bat', 'rat', 'elephant'] dictionary, not just acopy of a reference.
Ex: import copy
>>>spam[-1] >>>spam = ['A', 'B', 'C', 'D']
'elephant' >>>cheese = copy.copy(spam)
>>>cheese[1] = 42
(ii). slicing(): A slice is typed between square brackets, like an index, but it has two integers separated >>>spam
by a colon. ['A', 'B', 'C', 'D']
Ex: spam = ['cat', 'bat', 'rat', 'elephant'] >>>cheese
['A', 42, 'C', 'D']
>>>spam[0:4]
['cat', 'bat', 'rat', 'elephant'] (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.
(iii). append():To add new values to a list, use the append()method that adds the argument to the end of the Ex: import copy
list.
Ex: spam = ['cat', 'dog', 'bat']
>>>spam = ['A', 'B', 'C', 'D']
>>>spam.append('moose') >>>cheese = copy.copy(spam)
>>>cheese[1] = 42
>>>spam Ex: d={}
['A', 'B', 'C', 'D'] fori in num:
>>>cheese d.setdefault(i,0)
['A', 42, 'C', 'D'] d[i]=d[i]+1
print(d)
3. Explain different ways to delete an element from a list with suitable Python syntax and fori in d:
programming examples. print('Frequency of '+str(i)+' is '+str(d[i]))
----- 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. Output:
Ex: eggs = [1, 2, 3] Enter a multidigit number: 12342312445788
>>>del eggs[2] {'1': 2, '2': 3, '3': 2, '4': 3, '5': 1, '7': 1, '8': 2}
>>>del eggs[1] Frequency of 1 is 2
>>>del eggs[0]
Frequency of 2 is 3
eggs
Frequency of 3 is 2
[] Frequency of 4 is 3
(ii). remove():The remove() method is passed the value to be removed from the list it is
Frequency of 5 is 1
called on.
Frequency of 7 is 1
Ex: spam = ['cat', 'bat', 'rat', 'elephant']
Frequency of 8 is 2
>>>spam.remove('bat')
>>>spam 7. Read a multi-digit number (as chars) from the console. Develop a program to print the
['cat', 'rat', 'elephant'] frequency of each digit with suitable message.
-----d={}
4. Tuples are immutable. Explain with Python programming example. fori in num:
-----The tuple data type is typed with parentheses, ( and), instead of square brackets. d.setdefault(i,0)
Tuples are immutable. Tuples cannot have their values modified, appended, or removed. d[i]=d[i]+1 print(d)
Ex: eggs = ('hello', 42, 0.5) fori in d:
>>>eggs[1] = 99 print('Frequency of '+str(i)+' is '+str(d[i]))
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module> Output:
eggs[1] = 99 Enter a multidigit number: 12342312445788
TypeError: 'tuple' object does not support item assignment {'1': 2, '2': 3, '3': 2, '4': 3, '5': 1, '7': 1, '8': 2}
Frequency of 1 is 2
5. Explain how lists are mutable. Frequency of 2 is 3
-----A list value is a mutable data type: It can have values added, removed, or changed. Frequency of 3 is 2
Ex: spam = ['cat', 'bat', 'rat', 'elephant'] Frequency of 4 is 3
>>>spam.remove('bat') Frequency of 5 is 1
>>>spam Frequency of 7 is 1
['cat', 'rat', 'elephant'] Frequency of 8 is 2
Ex::spam = ['cat', 'dog', 'bat']
>>>spam.insert(1, 'chicken') 8. Program to find mean, variance and standard deviation.
>>>spam -----import math
data=[1,4,3,5,6]
['cat', 'chicken', 'dog', 'bat']
def mean(data):
n=len(data)
6. Explain with a programming example to each: (ii) get() (iii) setdefault() mean=sum(data)/n
----- get():dictionaries have a get() method that takes two arguments: the key of the value to retrieve return mean
and a fallback value to return if that key does not exist. print(“the mean is" + str (mean(data)))
Ex: picnicItems = {'apples': 5, 'cups': 2}
def variance(data):
>>>'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.' n=len(data)
>>>'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.' mean=sum(data)/n
'I am bringing 0 eggs.' dev=[(x-mean)**2 for x in data]
Setdefault(): In setdefault methodThe first argument passed to the method is the key to check for, var=sum(dev)/n
and the second argument is the value to set at that key if the key does not exist. If the key does exist, returnvar
the setdefault() method returns the key’s value.
print("the variance is "+str(variance(data))) 'o': 2,
defstandardDev(data): 'p': 1,
var=variance(data) 'r': 5,
's': 3,
std=math.sqrt(var)
't': 6,
return std 'w': 2,
print("the standard deviation is "+str(standardDev(data))) 'y': 1}
Output:
the mean is 3.8
the variance is 2.96
the standard deviation is 1.7204650534085253
3. Explain with suitable Python program segments: (i) os.path.basename() (ii) os.path.join(). 7. Develop a program to sort the contents of a text file and write the sorted contents into a
iii. os.path.dirname() separate text file.
-----(i)os.path.basename(): Calling os.path.basename(path) will return a string of everything that ----- list1=[]
comes after the last slash in the path argument. file=open("D:\\hello1.txt")
Ex:path = 'C:\\Windows\\System32\\calc.exe' var=file.readlines()
>>>os.path.basename(path) print(var)
'calc.exe' for i in var:
(ii) os.path.join(): os.path.join() will return a string with a file path using the correct path separators. list1.append(i.strip())
Ex: import os print(list1)
>>>os.path.join('usr', 'bin', 'spam') list1.sort()
'usr\\bin\\spam' print(list1)
iii. os.path.dirname(): Calling os.path.dirname(path) will return a string of everything that comes file.close()
before the last slash in the path argument. file1=open("D:\\hello2.txt",'w')
Ex:>>>os.path.dirname(path) for i in list1:
'C:\\Windows\\System32' file1.write(i+'\n')
file1.close()
4. Explain reading and saving python program variables using shelve module with suitable Output:
Python program. ['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
-----You can save variables in your Python programs to binary shelf files using the shelve module. Hello1.txt:['vidya', 'anugna', 'shruthi', 'bindu']
The shelve module will let you add Save and Open features to your program. Hello2.txt:['anugna', 'bindu', 'shruthi', 'vidya']
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. 8. Explain with example isalpha(), isalnum(), isspace(), isdecimal(), isupper(), islower().
Ex: import shelve -----(i). isupper(), islower():The isupper() and islower() methods will return a Boolean True value if
>>>shelfFile = shelve.open('mydata') the string has at least one letter and all the letters are uppercase or lowercase, respectively.
>>>cats = ['Zophie', 'Pooka', 'Simon'] Ex: spam = 'Hello world!'
>>>shelfFile['cats'] = cats >>>spam.islower()
>>>shelfFile.close() False
>>> 'HELLO'.isupper()
5. Develop a Python program to read and print the contents of a text file. True
----- list1=[] ii. isalpha(): isalpha() returns True if the string consists only of letters and is not blank.
file=open("D:\\hello1.txt") > 'hello'.isalpha()
var=file.readlines() True
print(var) >>> 'hello123'.isalpha()
for i in var: False
list1.append(i.strip()) iii. isalnum(): isalnum() returns True if the string consists only of letters and numbers and is not
print(list1) blank.
list1.sort() 'hello123'.isalnum()
print(list1) True
file.close() iv. isdecimal():isdecimal() returns True if the string consists only of numeric characters and is not
file1=open("D:\\hello2.txt",'w') blank.
for i in list1: '123'.isdecimal()
file1.write(i+'\n') True
file1.close() v. isspace(): returns True if the string consists only of spaces, tabs, and newlines and is not blank.
>>> ' '.isspace()
True
vi. istitle(): istitle() returns True if the string consists only of words that begin with an uppercase letter
followed by only lowercase letters.
>>> 'This Is Title Case'.istitle()
Module 4
True
1. Explain permanent delete and safe delete with a suitable Python programming example to
9. Write a program to accept string and display total number of alphabets. each.
-----defcount_alphabets(input_string): ----- Permanently Deleting Files:
alphabet_count = 0 To delete a folder and all of its contents, you use the shutil module.
for char in input_string: • Calling os.unlink(path) will delete the file at path.
ifchar.isalpha(): # check if the character is alphabetic • Calling os.rmdir(path) will delete the folder at path. This folder must be
alphabet_count += 1 empty of any files or folders.
returnalphabet_count • Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will
input_string = input("Enter a string: ") also be deleted.
num_alphabets = count_alphabets(input_string)
Ex: import os
print(f"Total number of alphabets in the string: {num_alphabets}")
for filename in os.listdir():
10. Develop a python code to determine whether give string is a palindrome or not. if filename.endswith('.rxt'):
-----def isPalindrome(s): os.unlink(filename)
return s == s[::-1] Safe Deletes with the send2trash Module:
s = "malayalam" A much better way to delete files and folders is send2trash module.
ans = isPalindrome(s) send2trash will send folders and files to your computer’s trash or recycle bin instead of permanently
if ans:
deleting them.
print("Yes")
else: Ex: import send2trash
print("No") >>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')
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 7. Develop a program that uses class Student which prompts the user to enter marks in three
return p subjects and calculates total marks, percentage and displays the score card details.
iv). passing an instance (or objects) as an argument: ----- class Student:
You can pass an instance as an argument in the usual way. For example: def __init__(self):
def print_point(p): self.name=input('Enter the student name: ')
print('(%g, %g)' % (p.x, p.y)) self.usn=input('Enter the student USN: ')
print_point takes a point as an argument and displays it in mathematical notation. To invoke it, you self.marks =[]
def getMarks(self):
can pass blank as an argument:
total = 0
>>> print_point(blank)
for i in range(3):
(3.0, 4.0) self.marks.append(int(input('Enter the marks of subject '+str(i+1)+': ')))
total+=self.marks[i]
5. Define pure function and modifier. Explain the role of pure functions and modifiers in self.marks.append(total)
application development with suitable python programs.
def Display(self):
----- Pure functions:
print('------------**********-------------',end='\n\n')
pure function because it does not modify any of the objects passed to it as arguments and it
print('Student\'s score card: ')
has no effect, like displaying a value or getting user input, other than returning a value.
print('Student name:', self.name)
Ex: def add_time(t1, t2): print('Student USN:', self.usn)
sum = Time() 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