0% found this document useful (0 votes)
2 views

Python Question Bank With Answers. (1)

Uploaded by

Rehan Pasha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Question Bank With Answers. (1)

Uploaded by

Rehan Pasha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

print('It is good to meet you, ' + myName)

Python important questions print('The length of your name is:')


print(len(myName))
print('What is your age?')
Module 1 myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
1. List and explain math operators used in python with example.
----- The print() Function
The print() function displays the string value inside the parentheses on the screen.
Ex: print('Hello world!')
print('What is your name?')
The input() Function
The input() function waits for the user to type some text on the keyboard
and press enter.
Ex: myName = input()
The len() Function
You can pass the len() function a string value (or a variable containing a string), and the function
evaluates to the integer value of the number of characters in that string.
Ex: print('The length of your name is:')
Precedence: print(len(myName))
The ** operator is evaluated first; The str()
The *, /, //, and % operators are evaluated next, from left to right; The str() function can be passed an integer value and will evaluate to a string value version of it.
The + and - operators are evaluated last (also from left to right).
Ex: print('I am ' + str(29) + ' years old.')
Parentheses is used to override the usual precedence if needed.
Ex: (5 - 1) * ((7 + 1) / (3 - 1)) I am 29 years old.
int(), and float() Functions
4 * ((7 + 1) / (3 - 1)) int(), and float() functions will evaluate to the string, integer, and floating-point forms of the value
you pass, respectively.
4 * ( 8 ) / (3 - 1)) Ex: int(1.25)
1
4*(8)/(2) float('3.14')
3.14
4 * 4.0
4. Write a python program to check whether number is even or odd.
16.0 ----- defevenOdd( x ):
if (x %2==0):
2. What is a String? Explain String Concatination and Replication. print("even")
----- String is a collection of Characters.
else:
String Concatenation.
When + is used on two string values, it joins the strings as the string concatenation operator. print("odd")
Ex: 'Alice' + 'Bob' x=int(input(“Enter the number”))
'AliceBob' evenOdd(x)
Replication.
When the * operator is used on one string value and one integer value, it becomes the string 5. With Python programming examples to each, explain the syntax and control flow diagrams
replication operator. of break and continue statements.
'Alice' * 5 ----- break
'AliceAliceAliceAliceAlice' 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.
3. Write a python program and explain the following functions: int(), str(), float(), print(), len() while True:
and input(). print('Please type your name.')
----- print('Hello world!') name = input()
print('What is your name?') if name == 'your name':
myName = input() break
print('Thank you!')

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.

A while statement always consists of the following:


The while keyword
A condition (that is, an expression that evaluates to True or False)
A colon
Starting on the next line, an indented block of code (called the whileclause)
Example: spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1 9. With an example explain user defined functions.
----- All the functions that are written by any of us come under the category of user-defined functions.
Below are the steps for writing user-defined functions in Python.
 In Python, a def keyword is used to declare user-defined functions.
 An indented block of statements follows the function name and arguments which contains the
body of the function.
Syntax:
deffunction_name():
statements
The function may take arguments(s) also called parameters as input within the opening and closing
parentheses, just after the function name followed by a colon.
Syntax:
deffunction_name(argument1, argument2, ...):
statements
An argument is a parameter that assumes a default value if a value is not provided in the function
call for that argument.

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

9. Explain use of in and not in operators.


----- We can determine whether a value is or isn’t in a list with the in and not inoperators.in and not in
Module 3
are used in expressions andconnect two values. 1. Explain Python string handling methods with examples: split(),endswith(), ljust(), center(),
Ex: 'howdy' in ['hello', 'hi', 'howdy', 'heyas'] lstrip(),join(), startswith(),rjust(),strip(),rstrip().
True -----i. join(): The join() method is useful when you have a list of strings that need to be joined
>>>spam = ['hello', 'hi', 'howdy', 'heyas'] together into a single string value.
>>>'cat' in spam Ex: ', '.join(['cats', 'rats', 'bats'])
False 'cats, rats, bats'
ii. split(): The split() method is called on a string value and returns a list of strings.
>>>'howdy' not in spam
Ex: 'My name is Simon'.split()
False ['My', 'name', 'is', 'Simon']
>>>'cat' not in spam iii. endswith(),startswith():The startswith() and endswith() methods return True if the string value
True they are called on begins or ends (respectively) with the string passed to the method; otherwise, they
return False.
10. Write a program to count the frequency of characters using module PrettyPrint(PPrint). Ex: 'Hello world!'.startswith('Hello')
-----The pprint() and pformat() functions that will “pretty print” a dictionary’s values. This is helpful True
when you want a cleaner display of the items in a dictionary than what print() provides. >>> 'Hello world!'.endswith('world!')
Ex: import pprint True
message = 'It was a bright cold day in April, and the clocks were striking iv. strip(), rstrip(), lstrip():The strip() string method will return a new string without any whitespace
thirteen.' characters at the beginning or end. The lstrip() and rstrip() methods will remove whitespace
count = {} characters from the left and right ends, respectively
for character in message: Ex: spam = ' Hello World '
count.setdefault(character, 0) >>>spam.strip()
count[character] = count[character] + 1 'Hello World'
pprint.pprint(count) >>>spam.lstrip()
'Hello World '
O/P: >>>spam.rstrip()
{' ': 13, ' Hello World'
',': 1, v. ljust(), rjust(), center():The rjust() and ljust() string methods return a padded version of the string
'.': 1, they are called on, with spaces inserted to justify the text.
'A': 1, Ex: 'Hello World'.rjust(20)
'I': 1, ' Hello World'
'a': 4, >>> 'Hello'.ljust(10)
'b': 1, 'Hello '
'c': 3, The center() string method works like ljust() and rjust() but centers the text rather than justifying it to
'd': 3, the left or right
'e': 5, Ex: 'Hello'.center(20)
'g': 2, ' Hello
'h': 3, 2. Explain the concept of file path. Also explain absolute and relative path.
'i': 6, -----A file has two key properties: a filename (usually written as one word) and a path. The path
'k': 2, specifies the location of a file on the computer.
'l': 3, It has directories, folders and files.
'n': 4, Ex: c:\users\documents\file.txt
Absolute path: An absolute path, which always begins with the root folder. There are also the dot (.) Output:
folders. ['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
Calling os.path.abspath(path) will return a string of the absolute path of the argument. This is an easy Hello1.txt:['vidya', 'anugna', 'shruthi', 'bindu']
way to convert a relative path into an absolute one. Hello2.txt:['anugna', 'bindu', 'shruthi', 'vidya'
Ex: os.path.abspath('.')
'C:\\Python34' 6. Develop a Python program find the total size of all the files in the given.
Relative path():A relative path, which is relative to the program’s current working directory. There -----Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.
are also thedot-dot (..) folders. Program:
Calling os.path.relpath(path, start) will return a string of a relative path from the start path to path. If totalSize = 0
start is not provided, the current working directory is used as the start path. for filename in os.listdir('C:\\Windows\\System32'):
Ex: os.path.relpath('C:\\Windows', 'C:\\') totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
'Windows' print(totalSize)

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')

2. Develop a program to backing Up a given Folder (Folder in a current working directory)


into a ZIP File by using relevant modules and suitable methods.
----- import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder) # make sure folder is absolute
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
backupZip.write(foldername)
for filename in filenames:
if filename.startswith(os.path.basename(folder) + '_') and
filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python311\\PES’)
Output: 'C:\\bacon_backup'
Creating PES_1.zip... (iii). shutil.move(): Calling shutil.move(source, destination) will move the file or folder at the path
Adding files in C:\Users\PC\AppData\Local\Programs\Python\Python311\PES... source to the path destination and will return a string of the absolute path of
Adding files in C:\Users\PC\AppData\Local\Programs\Python\Python311\PES\pes1... the new location.
Done. Ex: import shutil
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
3. Explain the role of Assertions in Python with a suitable program. 'C:\\eggs\\bacon.txt'
----- An assertion is a sanity check to make sure your code isn’t doing something obviously wrong.
These sanity checks are performed by assert statements. If the sanity check fails, then an 6. Develop a Python program to traverse the current directory by listing subfolders and files.
AssertionError exception is raised. ----- The os.walk() function is passed a single string value: the path of a folder.
import os
assert statement consists of the following:
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
• The assert keyword
print('The current folder is ' + folderName)
• A condition (that is, an expression that evaluates to True or False)
for subfolder in subfolders:
• A comma
print('SUBFOLDER OF ' + folderName + ': ' + subfolder
• A string to display when the condition is False
for filename in filenames:
Ex: podBayDoorStatus = 'open' print('FILE INSIDE ' + folderName + ': '+ filename)
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".' print('')
>>> podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I can't do that.''
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".' 7. Explain the support for Logging with logging module in Python.
Traceback (most recent call last): ----- Python’s logging module makes it easy to create a record of custom messages that you write.
AssertionError: The pod bay doors need to be "open". These log messages will describe when the program execution has reached the logging function call
and list any variables you have specified at that point in time.
4. Develop a program with function named Divexp which takes two parameters a,b and c. Ex: import logging
Write assertion foe a>0 and raise exception for b=0. logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s -
----- def DivExp(a,b): %(message)s')
assert a>0,"a is greater than zero"
logging.debug('Start of program')
if b==0:
raise Exception("value of b cannot be zero")
else: def factorial(n):
c=a/b logging.debug('Start of factorial(%s%%)' % (n))
return c total = 1
a=int(input("enter the value of A")) for i in range(n + 1):
b=int(input("enter the value of B"))
total *= i
try:
print(DivExp(a,b)) logging.debug('i is ' + str(i) + ', total is ' + str(total))
except Exception as err: logging.debug('End of factorial(%s%%)' % (n))
print(err) return total
Output: print(factorial(5))
enter the value of A4 logging.debug('End of program')
enter the value of B0
value of b cannot be zero O/P: 2015-05-23 16:20:12,664 - DEBUG - Start of program
2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)
5. Explain the functions with examples: (i) shutil.copytree(), (ii). shutil.copy, (iii) shutil.move() 2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0
(iv) shutil.rmtree(). 2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0
----- The shutil module provides functions for copying files, as well as entire folders. 2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0
(i). shutil.copy(): Calling shutil.copy(source, destination) will copy the file at the path 2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0
source to the folder at the path destination. 2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0
Ex: shutil.copy('C:\\spam.txt', 'C:\\delicious') 2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0
'C:\\delicious\\spam.txt' 2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)
0
(ii) shutil.copytree(): The shutil.copytree() call creates a new folder named bacon_backup with 2015-05-23 16:20:12,684 - DEBUG - End of program
the same content as the original bacon folder.
Ex: import shutil, os
>>> os.chdir('C:\\')
>>> shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
8. Explain logging levels in logging module.
----- Logging levels provide a way to categorize your log messages by importance.
There are five logging levels:
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

The __str__ method:


__str__ is a special method, like __init__, that is supposed to return a string representation
of an object.
Ex: inside class Time:
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
When you print an object, Python invokes the str method:
>>> time = Time(9, 45)
>>> print(time)
9. Explain Idle debug control window.
----- The debugger is a feature of IDLE that allows you to execute your program one line at a time. 09:45:00
The debugger will run a single line of code and then wait for you to tell it to continue.
The program will stay paused until you press one of the five buttons in the Debug Control window: 2. Explain the program development concept ‘prototype and patch’ with suitable example.
Go, Step, Over, Out, or Quit. ----- 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.
(i). Go: Clicking the Go button will cause the program to execute normally until it
Ex: Here is a function that converts Times to integers:
terminates or reaches a breakpoint.
def time_to_int(time):
(ii). Step: Clicking the Step button will cause the debugger to execute the next line of code and then pause minutes = time.hour * 60 + time.minute
again. The Debug Control window’s list of global and local variables will be updated if their values change. If seconds = minutes * 60 + time.second
the next line of code is a function call, the debugger will “step into” that function and jump to the first line of
return seconds
code of that function.
And here is a function that converts an integer to a Time
(iii). Over Clicking the Over button will execute the next line of code. The function’s code will be def int_to_time(seconds):
executed at full speed, and the debugger will pause as soon as the function call returns. time = Time()
(iv). Out: Clicking the Out button will cause the debugger to execute lines of code at full speed until it returns minutes, time.second = divmod(seconds, 60)
from the current function. time.hour, time.minute = divmod(minutes, 60)
return time
(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.
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: ')) sum.hour = t1.hour + t2.hour
b=Complex() sum.minute = t1.minute + t2.minute
b.real=int(input('Enter the real part of b: ')) sum.second = t1.second + t2.second
b.img=int(input('Enter the img part of b: ')) return sum
c=sum(a,b) Modifiers:
print(c.real,'+',c.img,'j') Sometimes it is useful for a function to modify the objects it gets as parameters. In that case,
Output: the changes are visible to the caller. Functions that work this way are called modifiers.
Enter the real part of a:2 Ex: def increment(time, seconds):
Enter the img part of a:3 time.second += seconds
Enter the real part of b:4
if time.second >= 60:
Enter the img part of b:5
time.second -= 60
6+9j
time.minute += 1
4. Explain the following with syntax and suitable code snippet: i) Class definition ii) if time.minute >= 60:
instantiation iii) passing an instance (or objects) as an argument iv) instances as return time.minute -= 60
values. time.hour += 1
----- i) Class definition: A class is a programmer-defined which acts as a blue print or a prototype.
A class definition looks like this: 6. Define class and object, construct class called rectangle and initialize it with
class Point: height=100,width=200.Write a program to display the center of a rectangle.
"""Represents a point in 2-D space.""" ----- A class is a programmer-defined which acts as a blue print or a prototype.
The header indicates that the new class is called Point. The body is a docstring that explains Creating a new object is called instantiation, and the object is an instance of the class.
class Rectangle:
what the class is for.
box = Rectangle()
ii) instantiation: Creating a new object is called instantiation, and the object is an instance of the box.width = 100.0
class. When instance is printed, Python tells you what class it belongs to and where it is stored box.height = 200.0
in memory. box.corner = Point()
Ex: blank = Point() box.corner.x = 0.0
>>> blank box.corner.y = 0.0

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

You might also like