[Go to site: main page, start]

0% found this document useful (0 votes)
30 views12 pages

Python Programming Exam Paper 2023

This document is a question paper for a Programming using Python course, intended for B.Sc. (H) Computer Science students in their first semester. It includes instructions for candidates, a compulsory Section A with various programming tasks, and Section B with additional programming questions. The paper covers topics such as algorithms, functions, data structures, and exception handling in Python.

Uploaded by

lessgojee2024
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)
30 views12 pages

Python Programming Exam Paper 2023

This document is a question paper for a Programming using Python course, intended for B.Sc. (H) Computer Science students in their first semester. It includes instructions for candidates, a compulsory Section A with various programming tasks, and Section B with additional programming questions. The paper covers topics such as algorithms, functions, data structures, and exception handling in Python.

Uploaded by

lessgojee2024
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

[This question paper cont ains 12 printed pages.

Your Roll No...[Link] 7ouo


Sr. No. of Question Paper : 1020 D

Unique Paper Code : 2342011101

Name of the Paper : Programming using Python


(DSC-1)
Name of the Course : [Link]. (H) Computer Science
Semester : I

Duration: 3 Hours Maximum Marks : 90

Instructions for Candidates

1. Write your RollNo. on the top immediately on receipt


of this question paper.

2. Section Ais compulsory.


3. Attempt any 4 questions from Section B.
4. Parts of a question must be answered together.

SECTION A

(Compulsory)

to solve
1. (a) What is an algorithm? Write an algorithm
the quadratic equation. (4)
P.T.0.
1020 2

(b) Write a function checkPrime(n) to check whether


the given number n is prime or not. The function
should return 1 if the number n is prime else 0
Call this function in main( ) to check the number
input by the user. (4)
(c) Evaluate the following expressions: (4)

(i) 9+3*2**2 != 9//4-2 and 'hello' >= 'Hello


world'

(ii) 20 ^ -22 & -5

(d) Consider the dictionary groupDict representing


student details of a group. (4)
groupDict is defined as follows :

groupDict = {'group': {
'student': {'name': 'Mike',
'marks': {physics: 70, history': 80}
}

'section': 'A'

Write the python code snippets for the following


operations :
1020 3

() Access the value of the subject Ehemistry.

(ii) Extract the value of the key group, and


use the default value as -1 if key is not
found.

(ii) Create a copy of a groupDict into a


dictionary object newGroup.

(iv) print the dictionary newGroup after


removing the element with the key section.

(e) Define a class Rectangle having the following


structure: (6)

Attributes: length, breadth


Methods: init () for initializing the attributes.

getLength() which returns the length of the


rectangle.

perimeter( ) which returns the perimeter of


the rectangle.

(f) Find the output for the following python scripts:


(8)

P.T.0.
1020 4

(i) myString = 'Hello Everyone, Welcome to the session!"


print(myString [len(myString) : -1)
print(myString (:-15] t myString [-15:)
print([Link]('Welcome')
print([Link](to'))

(i) X =('Red', 'Blue', 'Green')


Y = (Yellow','White']
[Link](Y)
[Link](23)
[Link]()
[Link]('Yellow')
print(X)
print(Y)

(11i) try:
num = 8

print(num + 'hello')
print(num / 4)
except ZeroDivisionError:
print(Divided by zero')
except(ValueError,TypeError):
print(Error occurred)
finally:
print('Stop')
1020 5

(iv) monthDays =(Januray': 31,'Fcbruary': 28,March': 31)


Month = monthDays
Month['Fcbruary'] +=1
print('monthDays before clear-->,monthDays)
print('Month before clcar-->, Month)
[Link]()
print('month Days after clear-->, monthDays)
print('Month after clear-->, Month)

SECTION B

2. (a) Write a program that accepts x and n as input to


compute the following series. (6)
x3
+" nterms
2! 3! 4!

(b) Consider the following code snippet (9)

for k in 'Computer Science':


if k= 'e':

S1
print(k, end = ", ")

Compare the output when SI is replaced with each


of the following statements:

P.T.0.
1020 6

(i) break

(ii) continue

(ii1) pass

3. (a) Consider the following tuples (6)

T1 =(100, 200, 300)

T2 = ('Monday', "Tuesday', "Wednesday')

(i) Write a function swapTuple (T1, T2) to


swap the values of T1 and T2.

The expected output is as follows:


TI = (Monday', Tuesday', Wednesday')
T2 = (100, 200, 300)

(ii)) Write a function mergeTuple(T1, T2) to


return a list of tuples containing the
corresponding element from tuples TI and
T2. The expected output is as follows :

T3 = [('Monday', 100), ("Tuesday', 200).


("Wednesday', 300)]
1020 7

(b) Consider list LIas follows : (9)

LI = [100, 200, 300, [400,500|]|

Writecode snippets to create the following lists :


() L2 as ashallow copy of LI

(ii) L3 as a deep copy of L1.

Demonstrate the effect of the following


modifications in L1, L2 and L3:

(i) LI[2] = 900

(ii) LI[3][O] = 700

4. (a) Write a function doubleDict() that creates the


dictionary Dictl where the keys are numbers
between 1 and 5 and values are twice the keys.
For example: if the key is 5, its value is 10. The
function should return the dictionary Dictl.

Write aprogram that calls doubleDict() and prints


the values of the following operations when applied
to the Dict1.

(1) maximum key

(i1) sum of keys (7)


P.T.0.
1020 8

(b) Consider two lists ILstl and Lst2 declared as


follows : (8)

Lstl =['green', 'bluc']

Lst2 =(blue', 'yellow']

Write a python script to do the following:

(i) Convert list Lstl as set S1 and Lst2 as


set $2.

(ii) Add the elements of the list ['black', 'cyan']


to S2.

(iii) Find the symmetric difference between sets


S1 and S2.

(iv) Create Set newSct using set

comprehension containing elements of S1


with 's' added at the end of each element.
The newSet should appear as:

newSet = ('blues', 'greens'}


5. (a) Consider the fuetion
that COmputes the percentage(marks, total)
percentage of marks for a
student. (6)
1020

def perccntage (marks, total):


try:

percent = (marks/total) * 100


Cxcept ValucError:
print("Value Error')
except TypeError:
print(Type Error')
except ZeroDivisionError:
print('Zero Division Error')
except:

print(Any other error')


else:

print(percent)
finally:
print('Completed!")
Explain the output corresponding to the following
function calls.

() percentage (17.0, 20.0)


(i) percentage (19.0, 0.0)

P.T.0.
1020 10

(iii) percentage ("200.0", 200.0)

(b) Definc the following functions to perform the


operations on astring. (9)

(i) countVowel(Strl)to count the vowels in a


string.

(ii) replaceChar(Strl) toreplace alloccurrence


of the character 'a' with a space.

(i) reverseString(Strl) to reverse a string


Write a program to call these functions and provide
the output for the given string Strl.

Strl = 'Happiness depends upon ourselves!"'

6. (a) Find the error(s) in the following code snippets:


(3)
(i) filel = open('Myfile, 'w)

[Link]()

[Link]()

(ii) tuplel = (2120, 'abc')


del tuplel[0]
1020

(b) Explain the type of exception raised in the following


statements : (4)

(i) x=0
print(5/x)

(i) print(The amount for the day is:'+ 300)

(ii) int('Morning')

(iv) Ll = [11,22,33,44,55]
print(LI[5])

(c) Describe the following methods for the class


objects with suitable examples. (8)

i) init

(ii)_str

(ii) del

(iv) main

7. (a) Write afunction sumDigits(Num) which computes


and returns
the sum of digits of a number Num
it
(5)

P.T.0.
1020 12

(b) Write a program to read a file myFile and perform


the following operations: (10)
(i) print the total number of lines in the file

(i) copy even lines of the file to afile named


evenFile and odd lines to another file named
oddFile.

Common questions

Powered by AI

In Python, a shallow copy of a list copies the references to the objects in the list, not the actual objects, so changes to nested objects will reflect in both lists. A deep copy creates independent copies of all objects within the list. For list L1 = [100, 200, 300, [400, 500]], modifying nested elements in a shallow copy affects both copies, but not in a deep copy. The document illustrates this using L2 for a shallow copy and L3 for a deep copy .

In Python loops, 'break' exits the loop immediately, skipping any remaining code and subsequent iterations. 'Continue' skips the current iteration and moves to the next iteration, without exiting the loop. 'Pass' is a null operation and simply passes control to the next iteration without affecting the loop conditions. These statements influence how the loop is executed without altering the actual structure of the data being iterated over .

The function `swapTuple(T1, T2)` swaps the values of two tuples, T1 and T2, returning them with their values interchanged. For example, given T1 = (100, 200, 300) and T2 = ('Monday', 'Tuesday', 'Wednesday'), after swapping, T1 becomes ('Monday', 'Tuesday', 'Wednesday') and T2 becomes (100, 200, 300).

In Python, dictionaries can be accessed and modified using keys. For instance, to access a value, use the syntax `dict[key]`. If a key might not exist, use `dict.get(key, default)` to avoid errors and provide a default value, such as -1. To modify a dictionary, you can add, change, or remove key-value pairs. For example, `copy_dict = dict.copy()` creates a shallow copy, and `del dict[key]` removes a key .

The try-except block in Python is used for handling exceptions to prevent the program from crashing. It allows you to execute code that might cause an error, and if an error occurs, the 'except' block catches it. For example, in the function `percentage(marks, total)`, exceptions such as ZeroDivisionError and TypeError are handled to prevent crashes, and a custom message is printed for each error type .

Sets in Python can be manipulated using operations like union, intersection, difference, and symmetric difference. For example, converting lists Lst1 and Lst2 to sets S1 and S2 allows the addition of new elements to S2 using `update()`, and finding the symmetric difference using `symmetric_difference()`, which returns elements present in either set but not in both. Additionally, set comprehensions can create new sets with specific modifications, such as appending 's' to each element of a set .

The function `mergeTuple(T1, T2)` pairs corresponding elements from two tuples and returns a list of these paired tuples. For example, given T1 = ('Monday', 'Tuesday', 'Wednesday') and T2 = (100, 200, 300), the function will return T3 = [('Monday', 100), ('Tuesday', 200), ('Wednesday', 300)]. This function effectively uses the `zip()` function to combine elements from both tuples .

Class-based encapsulation in Python involves bundling data (attributes) and methods (functions) to operate on the data into a single unit, a class. The Rectangle class demonstrates encapsulation by defining attributes like length and breadth, and methods such as `getLength()` and `perimeter()` to manipulate these attributes. The methods control how the attributes can be accessed or modified, promoting data integrity .

During file operations, using 'w' mode does not allow reading from the file, so calling `read()` on a file opened with mode 'w' raises an UnsupportedOperation error. In tuple manipulation, attempting to delete an item using `del tuple1[0]` on a tuple raises a TypeError, as tuples are immutable. These errors can be corrected by opening the file in read mode 'r', and converting the tuple to a list if modification is required .

An algorithm is a step-by-step procedure or formula for solving a problem. To solve a quadratic equation using an algorithm, you can follow these steps: 1) Input coefficients a, b, and c; 2) Calculate the discriminant: D = b^2 - 4ac; 3) If D > 0, calculate two real roots using (-b ± sqrt(D)) / (2a); if D = 0, calculate one real root using -b / (2a); if D < 0, indicate that there are no real roots .

You might also like