KEMBAR78
Assignment Holiday Homework | PDF | Comma Separated Values | Text File
0% found this document useful (0 votes)
26 views25 pages

Assignment Holiday Homework

The document is an assignment covering various topics related to functions and file handling in Python. It includes questions about arguments, global variables, return statements, and file operations, along with programming tasks such as creating, reading, and modifying CSV and binary files. Additionally, it presents case studies requiring the completion of Python code snippets to achieve specific functionalities.

Uploaded by

Jitesh Pahuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views25 pages

Assignment Holiday Homework

The document is an assignment covering various topics related to functions and file handling in Python. It includes questions about arguments, global variables, return statements, and file operations, along with programming tasks such as creating, reading, and modifying CSV and binary files. Additionally, it presents case studies requiring the completion of Python code snippets to achieve specific functionalities.

Uploaded by

Jitesh Pahuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

ASSIGNMENT: FUNCTIONS

1. What is the difference between Actual argument and Format argument? Explain with example
2. What is positional argument? Give example
3. What is the use of global keyword used in a function with the help of suitable example
4. Is return statement is compulsory in python function? How many values a return statement can return at a
time? If return statement is not used inside a function, what will be the return value of the function ?
5. Trace the flow of execution of the following program
i. def increment (x)
ii. x=x+1
iii.
iv. # main program
v. X=3
vi. print (x)
vii. increment (x)
viii. print(x)
6. What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables A and B.
import random
AR=[20,30,40,50,60,70,80,90]
A =random.randint(1,4)
B =random.randint(3,7)
for K in range(A, B +1):
print (AR[K],end=”#“)
(i) 30#40#50# (ii) 30#40#50#60# (iii) 50#60#70# (iv) 40#50#70#
7. Give the output of the following
x=3
def myfunc():
global x
x+=2
print(x, end=' ')
print(x, end=' ')
myfunc()
print(x, end=' ')
8. Write output of the following program
def func(x,y=10):
if (x%y==0):
x=x+1
return x
else:
y=y-1
return y
p,q=20,23
q=func(p,q)
print(p,"#",q)
p=func(q)
print(p,"#",q)
9. Write a function Swap(Arr,n ) in Python, which accepts a list Arr of numbers swaps all adjacent elements
of list .
Sample Input Data of the list Arr= [ 10,20,30,40,12,11] Output Arr = [20,10,40,30,11,12]
10. Ram , python programmer ,is working on a project which require him to define a function interest. He
define it as
def interest (Principal ,Rate= 0.15,time) :
But this code is not working, help him to identify the error in the above function and also correct it
11. What is the difference between local and global variable explain with example

12. What is the output of the following program?


def change (a=10):
a+=5
print((“a=”, a)
a = 20
change ( )
print(“a=”,a)
13. writte a function listchange(Arr,n) in python , whohc accepts a list Arr of numbers, the function will
replace the even number by value 10 and multiple odd number by 5.
Sample input data of the list is : [10,20,23,45] output = [10,10,115,225]

14. Write a function lenFOURword(L), where L is the list of elements (list of words) passed as argument to
the function. The function returns another list named ‘indexList’ that stores the indices of all four lettered
word of L.
For example:If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]
The indexList will have [2, 4]
15. Write a function LeftShift(Numlist, n) in Python, which accepts a list Numlist of numbers and n is a
numeric value by which all elements of the list are shifted to left.
Sample input data of the list : Numlist = [10, 20, 30, 40, 50, 60, 70], n=2
Output Numlist = [30, 40, 50, 60, 70, 10, 20]
16. Find the output of the following
def ChangeVal(M,N):
for i in range(N):
if M[i] %5 == 0:
M[i] //=5
if M[i] %3 == 0:
M[i] //=3
L = [25,8,75,12]
ChangeVal(L,4)
for i in L:
print(i,end="#")
17. What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variable number.
String = “CBSEONLINE”
Number = random.randint(0,3)
N=9
while String[N] ! = ‘L’ :
print (String[N] + String[Number] + “#” , end = ‘ ‘ )
Number = Number + 1
N = N-1
a. ES#NE#IO# ii) LE#NO#ON# iii) NS#IE#LO# iv) ES#NE#IS#
ASSIGNMENT FILE HANDLING

1. Write a program in python that defines and calls the user defined function :
Courier_add() : It takes the values from the user and adds the details to the CSV file courier.csv.
Each record consist of a list with field element as Cid, Sname, Source and
destination to store courier id ,senders name ,source and destination address
respectively.
Courier_search() : takes the destination as input and display all the courier records going to that
destination
2. Write a program in python that defines and calls the user defined function :
Add_book() : takes the details of the books and add them to a CSV file Book.csv. Each record
consist of a list with field element as B_id ,B_name and Pub to store book id, book
name and publisher respectively
Search_book() : take publisher name as input and count and display number of books published by
them.
3. Write a Program in Python that defines and calls the following userdefined functions:
ADD() – To accept and add data of an employee to a CSV file‘record.csv’. Each record consists of a
list with field elements as empid, name and salary to store employee id, employe ename
and employee salary respectively.
COUNTR() – To count the number of records present in the CSVfile named ‘record.csv’.
4. Write a Program in Python that defines and calls the following user defined functions:
A csv file "PATIENTS.csv" has structure [PID, NAME, DISEASE].Write the definition of a function
Countrec() in Python that would read contents of the file "PATIENTS.csv" and display the details of
those patients who have the DISEASE as 'COVID-19'. The function should also display the total number
of such patients whose DISEASE is 'COVID-19'.
5. A binary file “Toy.dat” has structure [TID, Toy, Status, MRP].
a) Write a user defined function CreateFile() to input data for a record and add to Toy.dat.
b) Write a function OnOffer() in Python to display the detail of those Toys, which has status as “ON
OFFER” from Toy.dat file.
6. A binary file “ITEMS.DAT” has structure (ID, GIFT, Cost). Write a function to write more items in
ITEM.DATWrite a function Economic() in Python that would read contents of the file “ITEMS.DAT” and
display the details of those ITEMS whose cost is greater then 2500
7. Tarun is a student, who wants to make a python program for Sports Department . He is using binary
file operations with the help of two user defined functions/modules.
(a) New_Entry() to create a binary file called SPORTS.DAT containing sports related material
information- item_id, item_name and item_qty.
(b) Show_Item() to display the item _name and item_qty of items which item_qty less than 5. In
case there is no item available that which quantity is less than 5 the function
displays message.
a) Update_item () to update the name of those tiem whose item id is 102.

8. A text file “PYTHON.TXT” contains alphanumeric text. Write a program that reads this text file and
writes to another file “PYTHON1.TXT” entire file except the numbers or digits in the file.
9. Write a function COUNTLINES( ) which reads a text file STORY.TXT and then count and
display the number of the lines which starts and ends with same letter irrespective of its
case . For example if the content of the text file STORY.TXT is :
The person has a sent a lovely tweet
Boy standing at station is very disturbed
Even when there is no light we can see
How lovely is the situation
The expected output is :
The Number of lines starting with same letter is 2
10. Write a user defined function in python named showlines() which reads contents of a text file named
STORY.TXT and displays every sentence in a separate line.
Assume that a sentence ends with a full stop(. , a question mark(‘?’) or an exclamation(!)
For example, if the content of file is :
Our parents told us that we must eat vegetables to be healthy. And it turns out, our parents were
right! So, what else did our parents tell?
Then the function should display the file content as follows:
Our parents told us that we must eat vegetables to be healthy.
And it turns out, our parents were right!
So, what else did our parents tell?
11. Write a function reverseFile()in Python, which should read the content of a text file
“TESTFILE.TXT” and display all its line in the reverse order.
Example: If the file content is as follows:
It rained yesterday.
It might rain today.
I wish it rains tomorrow too.
I love Rain.
The RainCount()function should display the output as:
.yadretsey deniar tI
.yadot niar thgim tI
.oot worromot sniar ti hsiw I
12. Assume that a text file named TEXT1.TXT already contains some text written into it ,write a function
named COPY(),that reads the file TEXT1.TXT and create a new file named TEXT2.TXT ,which shall
contain only those words from the file TEXT1.TXT which don’t start with an uppercase vowel(i.e. with
‘A’,’E’,’I’,’O’,’U’) ,for example if the file TEXT1.TXT contains
He can appoint any member of the Lok Sabha
then the file TEXT2.TXT shall contain
He can member of the Lok Sabha
13. Write the definition of a function ChangeGender() in Python, which reads the contents of a text file
"BIOPIC.TXT" and displays the content of the file with every occurrence of the word 'he' replaced by 'she'.
For example, if the content of the file "BIOPIC.TXT" is as follows :
Last time he went to Agra,there was too much crowd, which he did not like.
So this time he decided to visit some hill station.
The function should read the file content and display the output as follows:
Last time she went to Agra, there was too much crowd, which she did not like.
So this time she decided to visit some hill station.
CASE STUDY ASSIGNMENT: FILE HANDLING
1. Priti of class 12 is writing a program to create a CSV file “emp.csv”. She has written the following code
to read the content of file emp.csv and display the employee record whose name begins from “S‟ also
show no. of employee with first letter “S‟ out of totalrecord. As a programmer, help her to successfully
execute the given task.
Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
import _____ # Line-1
def snames():
with open(______) as csvfile: # Line-2
myreader = csv.___ (csvfile, delimiter=",") # Line-3
count_rec=0
count_s=0
for row in myreader:
if row[1][0].lower() == "s":
print(row[0],",",row[1],",",row[2])
count_s += 1
count_rec += 1
print(count_rec, count_s)
a) What should be written in Line-1?
b) In which mode should Priti open the file to print the data?
c) What should be written in Line-2 and Line-3?
2. Aditya is a Python programmer. He has written a code and created a binary file student.dat with
rollno, name, class and marks. The file contains 10 records. He now has to search record based on
rollno in the file student.dat As a Python expert, help him to complete the following code based on
the requirement given above:
import _______ #Statement 1
def searchrec():
r=int(input('Enter roll no of student to be searched'))
f=open(______________________) # staement2
found=False
try:
while True:
data=_______________ # statement 3
for rec in data:
if r==_______: # staement4
found=True
print('Name: ',rec[1])
print('Class : ',rec[2])
print('marks :',rec[3])
break
except Exception:
f.close()
if found==True:
print('Search successful')

AMIT KUMAR KUSHWAHA Page 1


else:
print('Record not exist')
a) Which module should be imported in the program? (Statement1)
b) Write the correct statement required to open a file student.dat in the required mode (Statement 2)
c) Which statement should Aditya fill in Statement 3 for reading data from binary file s tudent.dat. Also
Write the correct comparison to check existence of record (Statement4).
3. Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he has been
assigned an incomplete python code (shown below) to create a CSV File 'Student.csv' (content shown
below). Help him in completing the code which creates the desired CSV File. CSV File
1,AKSHAY,XII,A 2,ABHISHEK,XII,A
3,ARVIND,XII,A 4,RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code
import_____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()
Answer the following questions
a) Write the suitable code for blank space in line marked as Statement-1
b) Write the missing code for blank space in line marked as Statement-2?
c) Write function name (with argument) that should be used in the blank space of line marked as
Statement-3
d) Complete the statement-4 with suitable code.
e) Write the function name that should be used in the blank space of line marked as Statement-5 to
create the desired CSV File?
4. Your teacher has given you a method/function FilterWords() in python which read lines from a text file
NewsLetter.TXT, and display those words, which are lesser than 4 characters. Your teachers intentionally
kept few blanks in between the code and asked you to fill the blanks so that the code will run to find
desired result. Do the needful with the following python code.
def FilterWords():
c=0
file=open('NewsLetter.TXT', '_____') #Statement-1
line = file._____ #Statement-2
word = _____ #Statement-3
for c in word:
if _____: #Statement-4
print(c)
_________ #Statement-5
FilterWords()
AMIT KUMAR KUSHWAHA Page 2
a) Write mode of opening the file in statement-1?
b) Fill in the blank in statement-2 to read the data from the file.
c) Fill in the blank in statement-3 to read data word by word.
d) Fill in the blank in statement-4, which display the word having lesser than 4
e) Fill in the blank in Statement-5 to close the file.
5. Aditya has written a code and created a binary file record.dat with ItemNo, Itname and Price.As a Python
expert, help him to complete the following code based on the requirement given above:
Import ________________ #Statement 1
def Add_data():
fin = open("record.dat", " __ ") #Statement2
Lst = [áa’, 3.5, 66,77, 8, 10]
________________.(Lst, fin) #Statement3
print(“Record Added”)
fin.______________ #Statement4
Add_Rec()
a) Name the Module that Aditya should import in Statement 1
b) In which mode, Aditya should open the file to add data into the file in statement .
c) Fill in the blank in statement 3 to fetch the data to a file and statement 4 to close the file.
6. Anamika is a Python programmer. She has written a code and created a binary file data.dat with sid,
sname and marks. The file contains 10 records. She now has to update a record based on the sid entered
by the user and update the marks. The updated record is then to be written in the file extra.dat. The
records which are not to be updated also have to be written to the file extra.dat. If the sid is not found, an
appropriate message should to be displayed. As a Python expert, help him to complete the following code
based on requirement given above:
import ……………. #Statement 1
def update_data():
rec={}
fin=open("data.dat","rb")
fout=open("__________________ ") #Statement 2
found=False
eid=int(input("Enter student id to update their marks :: "))
while True:
try:
rec= __________ #Statement 3
if rec["student id"]==sid:
found=True
rec["marks"]=int(input("Enter newmarks:: "))
pickle.__________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The marks of student id ",sid," hasbeen updated.")
else:
print("No student with such id is not found")
fin.close()
fout.close()
a) Which module should be imported in the program? (Statement1)
b) Write the correct statement required to open a temporary filenamedextra.dat. (Statement 2)
AMIT KUMAR KUSHWAHA Page 3
c) Which statement should Anamika fill in Statement 3 to read the data from the binary file, data.dat and
in Statement 4 to write the updated data in the file, extra.dat?
7. Devi is a Python programmer. He has written a code and created a binary file record. datwith employeeid,
ename and salary. The file contains 10 records. He now hasto update a record based on the employee id
entered by the user and update the salary. The updated record is then to be written in the file temp.dat.
The records which are not to be updated also have to be written to the file temp.dat. If the employee id is
not found, an appropriate message should to be displayed. As a Python expert, help him to complete the
following code based on the requirement given above:
import ___________________ #Statement 1
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open(" -------“) ") #Statement 2
found=False
eid=int(input("Enter employee id to update theirsalary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary:: "))
pickle._________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," hasbeen updated.")
else:
print("No employee with such id is not found")fin.close()
fout.close()

a) Which module should be imported in the program? (Statement1)


b) Write the correct statement required to open a temporary file named temp.dat. (Statement 2)
c) Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat
and in Statement 4 towrite the updated data in the file, temp.dat?

AMIT KUMAR KUSHWAHA Page 4


QUESTIONS BASED ON ASSERTION REASONING

FILE HANDLING

ASSERTION AND REASONING based questions. Mark the correct choice as:
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True

1. Assertion (A): Binary files store all data in text format.


Reasoning (R): Binary files data remain in its original type.
2. Assertion (A): CSV file is a human readable text file where each line has a number of fields,
separated by commas or some other delimiter.
Reason (R): writerow() function can be used for writing into writer object.
3. Assertion (A): CSV stands for comma separated value.
Reason (R): CSV files are a common file format for transferring and storing data.
4. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a text
file.
Reason (R): The information is organized with one record on each line and each
5. Assertion (A):-Serialization is the process of transforming data to a stream of bytes
Reasoning (R):-It is also known as Pickling
6. Assertion (A): Access mode ‘a’ opens a file for appending.
Reason (R): The file pointer is at the end of the file if the file exists
7. Assertion (A); Binary file is faster than text file, so it is mostly used for storing data.
Reasoning (R): Text file stores fewer characters as compared to the binary file.
8. Assertion (A): with statement can be used to open a file and should be preferred over other ways to open
a file.
Reasoning (R): with statement is a block of statement that makes sure the file is closed in case of any run-
time error and buffer is cleared to avoid data loss.
9. Assertion(A) : The tell method will stores/get the current location of the file pointer.
Reasoning(R): Python seek method returns the current position of the file read/write pointer with the file.
10. Assertion (A) : Text file stores information in ASCII or Unicode characters.
Reason (R) : CSV stands for comma separated value. These files are common file format for transferring
and storing data.
11. Assertion (A):- The readlines() method in python reads all lines from a text file.
Reasoning (R):- The readlines() method returns the tuple of lines(string).
12. Assertion (A): writerow( ) function helps us to write multiple rows in a csv file at a time.
Reasoning (R) : Writing one row at a time in a csv file is not possible, we must write multiple rows at a
time.
13. Assertion (A) : With statement can be used to open any file, be it csv file or binary file and while using
with statement to open any file there is no need to close the file.
Reasoning (R) : With statement groups all the statements related to file handling and makes sure to close
the file implicitly. It closes the file even when any error occurs during the execution of
statements in a with statement
14. Assertion (A): A binary file in python is used to store collection objects like lists and dictionaries that can
be later retrieved in their original form using pickle module.
Reasoning (R): A binary files are just like normal text files and can be read using a text editor like
notepad.
15. Assertion (A): CSV module allows to write a single record into each row in CSV file using writerow()
function.
Reason (R): The writerow() function creates header row in csv file by default.
16. Assertion (A): A binary file stores the data in the same way as as stored in the memory.
Reason (R): Binary file in python does not have line delimiter.
17. Assertion(A): Pickling is the process by which a Python object is converted to a byte stream. 1
Reasoning(R) : load() method is used to write the objects in a binary file. dump() method is used to read
data from a binary file
18. Assertion (A):- If a text file already containing some text is opened in write mode the previous contents
are overwritten.
Reasoning (R):- When a file is opened in write mode the file pointer is present at the beginning position
of the file.
19. Assertion (A): CSV files are used to store the data generated by various social media platforms.
Reason (R): CSV file can be opened with MS Excel.
MCQ FROM FILE HANDLING - 1

1. Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is the file object. What is the
default value of reference_point?
a) 0 b) 1 c) 2 d) 3
2. To specify a different delimiter while writing into csv file, ……. argument is used withcsv.writer().
a) delimit b) delimiter c) delimited d) delimits
3. To cancel the EOL translation in csv file while writing the data __________argument is used with open().
a) newline b) next c) open d) EOL
4. Every record in a CSV file is stored in reader object in the form of a list using which method?
a) writer() b) append() c) reader() d) list()
5. If you are opening a binary file in read mode, then the file must exist otherwise what happens?
a) Compile time error occur c) Run-time error raises
b) Not any error raises d) None of these
6. Is it necessary to have header line as first line in csv file:
a) No b) Yes c) Both Yes and No d) None
7. In which format does the readlines( ) function give the output?
a) Integer type b) list type c) string type d) tuple type
8. Myfile=open(“class.txt”,”r”)
Str=Myfile.read(12)
The above code will be equal to:
a) file(“class.txt”,”r”).read(12) b) Myfile(“class.txt”,”r”).read(12)
b) file(“class.txt”,”r”).myfile.read(12) c) myfile(“class.txt”,”r”).read(12)
9. Identify the error in the following code:
import pickle
mix_data=[‘hundred’,2, [3,4,5]]
with open (‘mixeddata.dat’, ‘rb’) as fout:
pickle.dump(mix_data , fout)
a) Not any error is there b) with open (‘mixeddata.dat’, ‘w’)
c) with open (‘mixeddata.dat’, ‘wb’) d) None of these
10. Suppose the content Rhymes.txt is
Jack & Jill
Went up the hil
What will be the output of the following code ?
F= open(“Rhymes.Txt”)
L=F.readlines()
for i in L:
S=i.split()
print(len(S),end=”#”)
a) 2#4# b) 3#4# c) 2# d) 7#
11. Suppose the content Rhymes.txt is
One, two, three, four, five
Once I caught a fish alive.
F= open(“Rhymes.Txt”)
S=F.read()
print(S.count(’e’,20))
a) 20 b) 1 c) 3 d) 6

Page 1
12. The correct syntax of read() function from text files is:
a. file_object.read() b. file_object(read) c. read(file_object) d. file_object().read
13. Which of the following are the modes of both writing and reading in binary format in file?
a) wb+ b) w c) w+ d) wb
14. A text file student.txt is stored in the storage device. Identify the correct option out of the following options to open
the file in read mode.
i. myfile = open('student.txt','rb') ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r') iv. myfile = open('student.txt')
a) only I b) both i and iv c) both iii and iv d) both i and iii
15. Assume that the position of file pointer is at the beginning of 3rd line in a text file. Which of the following option can
be used to read all remaining lines?
(a) file.read() (b) file.readlines() (c) file.readline() (d) None of these
16. The _________ method of _____ module is used to read data from binary file :
a) read(), binary b) load(), pickle c) dump(), binary d) dump(), pickle
17. Which of the following modes will refer to binary data?
(a) r (b) wb (c) + (d) a
18. The Correct syntax of seek() is:
(a) File_object.seek(offset[,reference_point]) (b) seek(offset[,referece_point])
(c) seek(offset,file_object) (d) seek.file_object(offset)
19. Which of the following is not a correct Python statement to open a text file “Notes.txt” to write content into it?
a) F=open(‘Notes.txt’,’w’) b) F=open(‘Notes.txt’,’a’)
c) F=open(‘Notes.txt’,’A’) d) F=open(‘Notes.txt’,’w+’)
20. Which of the following option is the correct Python statement to read and display the first 10 characters of a text file
“Notes.txt”?
a) F=open(“Notes.txt”); print(F.load(10)) b) F=open(“Notes.txt”); print(F.dump(10))
c) F=open(“Notes.txt”); print(F.read(10)) d) F=open(“Notes.txt”); print(F.write(10))
21. Which of the following commands is used to open a file “c:\test.txt” for reading and writing data in binary format
only.
(a) myfile = open(‘c:\\test.txt’,’rb+’) (b) myfile = open(‘c:\test.txt\’,’wb’)
(c) myfile = open(‘c:\test.txt’,’w+’) (d) myfile = open(‘c:\\test.txt’,’rb’)
22. Which of the following functions do you use to write data in the binary format?
(a) write() (b) output() (c) dump() (d) send()
23. Method used to force python to write the contents of file buffer on to storage file is
a) count() b) read() c) flush() d) True
24. Which of the following is not a function / method of csv module in Python?
a. read() b. reader() c. writer() d. writerow()
25. Select the correct output of the following code Fp.seek(5,1)
a) Move file pointer five character ahead from the current postion
b)Move file pointer five character ahead from the beginning of a file
c)Move file pointer five character behind from the current postion
d)Move file pointer five character behind ahead from the end of a file

Page 2
ASSGNMENT -1 OUTPUT QUESTIONS

1. Find the output of the following code :


def compute(s):
x=[]
for i in range (len(s)):
a=s[i]
b=a.upper( )
if a not in x and b not in x:
if a>'p':
x.append(a.upper())
else :
x.append (a)
return x
print(compute("abracadabra"))
2. What possible outputs(s) expected to be displayed on screen at the time of execution of the Program from
the following code? Also specify the maximum values that can be assigned to each of the variables A and B.
import random
AR=[20,30,40,50,60,70,80,90]
A =random.randint(1,4)
B =random.randint(3,7)
for K in range(A, B +1):
print (AR[K],end=”#“)

(i) 30#40#50# (ii) 30#40#50#90# (iii) 50#60#70# (iv) 20#50#70#


3. Find the output of the following code :
str="Python123.com"
for i in range(len(str)):
if(str[i].isalpha()):
print(str[i-1])
if(str[i].isdigit()):
print(str[i])
4. Find the output of the following code :
s='mahender, singh, dhoni'
s1=s.split()
for i in s1:
if(i>'n'):
print(i.upper())
else:
print(i)
5. Find the output of the following code :
list1 = ["python", "list", 1952, 2323, 432]
list2 = ["this", "is", "another", "list"]
print(list1[1:4])
print(list1[1:])
print(list1[0])
print(list1 * 2)
print(list1 + list2)

AMIT KUMAR KUSHWAHA Page 1


6. Find the output of the following program
tuple1=(11, 22, 33, 44, 55 ,66)
list1 =list(tuple1)
new_list = []
for i in list1:
if i%2==0:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
7. Find the output of the following program
str1 ='P@ssW0rd',
str2 =""
for ch in str1:
if ch>='A' and ch<='Z':
ch=chr(ord(ch)+33)
elif ch>='a' and ch<='z':
ch=chr(ord(ch)-31)
else:
ch='*'
str2=ch+str2
print(str2)
8. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program
from the following code? Also specify the maximum values that can be assigned to each of the variable x.
import random
List=["Delhi","Mumbai","Chennai","Kolkata"]
for y in range(4):
x = random.randint(1,3)
print(List[x],end="#")
a. Delhi#Mumbai#Chennai#Kolkata# b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi# d. Mumbai# Mumbai #Chennai # Mumbai
9. a) If a = [5,4,3,2,1,0,5] evaluate the following expression
i. a[-1]
ii. a[a[a[a[3]+1]]]

b) What is the length of the tuple shown below : t = (((( ‘a’,1),’b’,’c’),’d’,2),’e’,3,5)

10. Find the output of the following program


s = "UVW"
L = [10,20,30]
d = {}
n = len(s)
for i in range (n):
d[L[i]]= s[i]
for k,v in d.items():
print (k,v,sep=”*”, end = “”)

AMIT KUMAR KUSHWAHA Page 2


ASSIGNMENT -2 OUTPUT QUESTIONS
1. Find the output of the following program
d={1:10, 2:20, 3:3}
d.setdefault(2,30)
d.setdefault(4,30)
d[1]=50
print(d)
2. What possible output(s) are expected to be displayed on screen at the time of execution of the program
from following code?
import random
LST=[5,10,15,20,25,30,35,40,45,50,60,70]
first = random.randint(3,8) -1
second = random.randint(4,9) -2
third = random.randint(6,11) -3
print(LST[first],"#", LST[second],"#", LST[third],"#")
a) 20#25#25# b) 30#40#70# c) 15#60#70# d) 35#40#60#
3. Find the output of the following
s1='Hello World!'
index=0
while index< (len(s1)-3):
print(s1[index], end=' ')
index =index+ 1
4. Find the output of the following
my_dict={ }
my_dict[1]=1
my_dict[‘1’]=2
my_dict[1.0]=4
print(my_dict)
5. Find the output of the following
fruits = { 'Apple': 100,'Orange': 200,'Banana': 400, 'pomegranate':600}
if 'Apple' in fruits:
del fruits['Apple']
print('Dictionary after deleting key =',fruits)
6. Find the output of the following
l = [6 , 3 , 8 , 10 , 4 , 6 , 7]
print( '@', l[3] - l[2])
for i in range (len(l)-1,-1,-2):
print( '@',l[i],end='' )

AMIT KUMAR KUSHWAHA Page 1


7. Find the output of the following
def Diff(N1,N2):
if N1>N2:
return N1-N2
else:
return N2-N1
NUM= [10,23,14,54,32]
for CNT in range (4,0,-1):
A=NUM[CNT]
B=NUM[CNT-1]
print(Diff(A,B),'#', end=' ')
8. Find the output of the following
p=5
def sum(q,r=2):
global p
p=r+q**2
print(p, end= '#')
a=10
b=5
sum(a,b)
sum(r=5,q=1)
9. Find the output of the following
s="welcome2cs"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m =m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)
10. Find the output of the following
v=25
def fun(ch):
v=50
print(v,end=ch)
v*=2
print(v, end=ch)
print(v, end="*")
fun("!")
print(v)

AMIT KUMAR KUSHWAHA Page 2


ASSIGNMENT -3 OUTPUT QUESTIONS
1. Find the output of the following
def func1(a):
a= a + '1'
a=a*2
print(a)
func1("Good")
2. Find the output of the following
a) L=[1,3,[6,5,7],82,11,92,[5,6,7]]
print(L[1:-2:2])
b) b = 1
for a in range(1, 10, 2):
b += a + 2
print(b)
3. Find the output of the following
def ChangeVal(M,N):
for i in range(N):
if M[i] %5 == 0:
M[i] //=5
if M[i] %3 == 0:
M[i] //=3
L = [25,8,75,12]
ChangeVal(L,4)
for i in L:
print(i,end="#")
4. Find the output of the following
Data = ["P",20,"R",10,"S",30]
Times = Add = 0
Alpha = ""
for C in range(1,6,2):
Times = Times + C
Alpha = Alpha + Data[C-1]+"$"
Add = Add + Data[C]
print(Times,Add,Alpha)
5. What possible output(s) are expected to be displayed on screen at the time of execution of the program
from the following code? Also specify the maximum values that can be assigned to each of the variable
number.
String = “CBSEONLINE”
Number = random.randint(0,3)
N=9
while String[N] ! = ‘L’ :
print (String[N] + String[Number] + “#” , end = ‘ ‘ ) Number
= Number + 1
N = N-1
a. ES#NE#IO# ii) LE#NO#ON# iii) NS#IE#LO# iv) ES#NE#IS#
6. Find the output of the following
def Alter(A=12,B=10):

AMIT KUMAR KUSHWAHA Page 1


A=A*B
B=A/B
print A,"@",B
return B
X=200
Y=300
X=Alter(X,Y)
print (X,"$",Y)
Y=Alter(Y)
print (X,"$",Y)
7. Find the output of the following
a=30
def call (x):
global a
if x%2==0:
x=x+a
else:
x=x-a
return(x)
print(call(67), end="#")
print(call(40),end="#")
8. Find the output of the following
val = 100
def display(N):
global val
val = 50
if N%14==0:
val = val + N
else:
val = val - N
print(val, end="@")
display(40)
print(val)
9. Find the output of the following
import random
string='COMPUTER'
for k in range(4):
pos=random.randint(3,6)
print(string[pos],end='')

i) PUTU ii) CMCP iii) ETTU iv) URER


10. Find the output of the following
L1 = [100,900,300,400,500]
START = 1
SUM = 0
for C in range(START,4):
SUM = SUM + L1[C]

AMIT KUMAR KUSHWAHA Page 2


print(C, ":", SUM)
SUM = SUM + L1[0]*10
print(SUM)

AMIT KUMAR KUSHWAHA Page 3


ASSIGNMENT -4 OUTPUT QUESTIONS
1. Find the output of the following
import random
sides = [“EAST”, “WEST”,”NORTH”,”SOUTH”]
N=random.randint(1,3)
Out=””
for I range (N,1,-1):
Out=Out+sides[I]
print(out)
a) SOUTHNORTH b) SOUTHNORTHWEST c) SOUTH d) EASTWESTNORTH
2. Find the output of the following
R=0
def change(A,B):
global R
A+=B
R+=3
print(A,B,sep =”#”, end="")
change(10,2)
print(R,end='%')
change(B=3,A=2)
3. Find the output of the following
def div(L,n):
for i in range(0,n):
if L[i]%5==0:
L[i]+=5
else:
L[i]=L[i]//2
t=[45,20,23,54,5]
div(t,len(t))
for i in t:
print(i,end="#")
4. Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-2])
5. Write the output of the code given below:
my_dict = {"name": "Aman", "age": 26}
my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items())
6. Find the output of the following
def calc(u):
if u%2==0:
return u+10
else :
return u+2
def pattern(M,B=2):
for I in range (0,B):

AMIT KUMAR KUSHWAHA Page 1


print(calc(I),M,end=’ ’)
pattern('#',4)
pattern('@',3)
7. Find the output of the following
def display(str):
m=""
for i in range(0,len(str)):
if (str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m+"#"
print(m)
display("ShailenderSir@Gmail.com")
8. Find the output of the following
def change(m,n=10):
global x
x+=m
n+=x
m=n+x
print(m,n,x)
x=20
change(10)
change(20)
9. Find the output of the following
import random
alpha = ['T','U','V','W']
dig=[2,6,7,3]
print("the winner is:",end ='')
print(alpha[random.randrange(0,3)],end='')
for i in range(4):
print(dig[random.randint(0,2)],end='')
i) The winner is : T7363 iii) The winner is : W7263
ii) The winner is : T6323 iv)The winner is : U3667
10. Find the output of the following
str = "Computer Science"
for i in range(0,len(str),5):
if i%2==0:
print(str[:i].upper(),'$')
else :
print(str[i:].lower(),'$')

AMIT KUMAR KUSHWAHA Page 2


ASSIGNMENT -5 OUTPUT QUESTIONS
1. Find the output of the following
def func(S):
k=len(S)
m= ""
for i in range(0,k):
if S[i].isalpha( ):
m=m+S[i].upper( )
elif S[i].isdigit( ):
m=m+"0"
else:
m=m+"#"
print(m)
func("Python 3.9")
2. Find the output of the following
str1="Exam2021"
str2=""
I=0
while I<len(str1):
if str1[I]>="A" and str1[I]<="M":
str2=str2+str1[I+1]
elif str1[I]>="0" and str1[I]<="9":
str2=str2+str1[I-1]
else:
str2=str2+"*"
I=I+1
print(str2)
3. Find the output of the following
F_list1=["Apple","Berry","Cherry","Papaya"]
F_list2=F_list1
F_list3=F_list1[:]
F_list2[0]="Guava"
F_list3[1]="Kiwi"
sum=0
for L in(F_list1,F_list2,F_list3):
if L[0]=="Guava":
sum+=1
if L[1]=="Kiwi":
sum+=20
print(sum)
4. Find the output of the following
my_dict={}
my_dict[(1,2,4)]=8
my_dict[(4,2,1)]=10

AMIT KUMAR KUSHWAHA Page 1


my_dict[(1,2)]=12
sum=0

for k in my_dict:
sum+=my_dict[k]
print(sum)
print(my_dict)
5. Find the output of the following
def calc(u):
if u%2==0:
return u+10
else:
return u+2
def pattern (M,B=2):
for CNT in range(0,B):
print(calc(CNT),M,end="")
print()
pattern("*")
pattern("#",4)
pattern("@",3)
6. Find the output of the following
L="earn"
X=""
L1=[]
count=1
for i in L:
if i in ['a','e','i','o','u']:
X=X+i.swapcase()
else:
if count%2!=0:
X+=str(len(L[:count]))
else:
X=X+i
count+=1
print(X)
7. Find the output of the following
str = "CBSE Digital India"
for i in range(len(str)-1,0,-1):
if str[i].isupper():
print(str[i].lower(),end="")
if i%2==0:
if str[i].islower():
print(str[i].upper(),end="")
else:
print('$',end="")
8. Find the output of the following
s="Hello2everyone"
n=len(s)

AMIT KUMAR KUSHWAHA Page 2


m=""
for i in range(0,n):
if (s[i]>='a' and s[i]<='m'):
m=m+s[i].upper()

elif (s[i]>='n' and s[i]<='z'):


m=m+s[i-1]
elif (s[i].isupper()):
m=m+s[i].lower()
else:
m=m+'*'
print(m)
Ans : hELLl*EeEeryoE
9. Find the output of the following
a=[i for i in range(1,10)]
for i in range(len(a)):
if a [i]%2==0:
print(a[i]-1)
else:
print(a[i]*2)
10. Find the output of the following
def ChangeList():
L=[]
L1=[]
L2=[]
for i in range(1,10):
L.append(i)
for i in range(10,1,-2):
L1.append(i)
for i in range(len(L1)):
L2.append(L1[i]+L[i])
L2.append(len(L)-len(L1))
print(L2)
ChangeList()
11. Find the output of the following
def func(b,c=5):
global a
a+=2*b
b+=3*c
c+=4*a
print (a,b,c,sep='#')
return b
a,x,y=7,3,9
y=func (x)
x=func (y,x)
print (a,x,y,sep='#')
12. Find the output of the following
def CALLME(n1=1,n2=2):

AMIT KUMAR KUSHWAHA Page 3


n1=n1*n2
n2+=2
print(n1,n2)
CALLME()
CALLME(3)

AMIT KUMAR KUSHWAHA Page 4

You might also like