0% found this document useful (0 votes)
13 views7 pages

Gujarat Public School Computer Science Exam Key

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

Gujarat Public School Computer Science Exam Key

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

GUJARAT PUBLIC SCHOOL - HALF YEARLY EXAM (2025-26)

SUBJECT: COMPUTER SCIENCE (083) - ANSWER KEY

Marks: 70 Time: 3 Hrs.

CLASS: XII-D/E/F DATE: 19/09/2025

SECTION A

1. C

2. B

3. B (void function)

4. D (readlines())

5. C ('-')

6. A open("[Link]","r")

7. A (ceil() — option shown as 'ciel()' in question)

8. B (try)

9. A (open())

10. C (global b)

11. D (A is false but R is True)

12. B (Integer)

13. B (w+)

14. C (readlines())

15. A (read)

16. C (except)

17. B (Stack)

18. A (-59.0)

19. B (lSo) [If string is "SoftSkills" without space]


20. A (A is True but R is False)

21. C (Both A and R are true and R is the correct explanation for A)

SECTION B

22.

(i) [Link](2, 200)

(ii) [Link]('.')

OR (alternative)

import statistics

print([Link](studentAge))

Matching:

A - ii

B-i

C - iv

D - iii

23. Exception: An event that occurs during program execution that disrupts the normal flow
of instructions. (Examples: ZeroDivisionError, ValueError, FileNotFoundError)

24.

Output:

('Learn Python ', 'with', ' fun and practice')

25.
Explicit type conversion (casting) - the programmer converts types deliberately, e.g. x =
int("12"), y = float(3)

Implicit type conversion - Python automatically converts types where needed, e.g. 3 + 2.5 ->
5.5 (int promoted to float)

(OR)

break stops the loop completely; continue skips to next iteration of loop.

26.

def countNow(PLACES):

for k, v in [Link]():

if len(v) > 5:

print([Link]())

Example:

PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}

Output:

LONDON

NEW YORK

27.

a) float('8.0+') -> ValueError (invalid literal)

float('2.0-') -> ValueError (invalid literal)

float('3') -> 3.0

b) abs(-80.6) -> 80.6

28.
Arguments: actual values passed to a function when calling it.

Parameters: variables listed in function definition that receive the values.

A function can return multiple values by returning a tuple, e.g. return a, b

SECTION C

29.

Prints:

[11, 14, 15, 17, 13, 18, 25]

[14, 15, 17]

(OR alternate)

Outputs first letters (uppercase) of sanctuary names whose last character is a vowel.

30.

Overflow: when a calculation exceeds the maximum limit a data type can hold (in some
languages).

PUSH: add an item to the top of a stack.

POP: remove and return the top item from a stack.

31.

Program to display words separated by '#':

with open('[Link]','r') as f:

for line in f:

words = [Link]()

print('# '.join(words) + ('#' if words else ''))

(OR reversefile function provided in question)


SECTION D

32. write() method writes a string to a file. Example:

with open('[Link]','w') as f:

[Link]("Hello\n")

33. Fill blanks:

file = open("[Link]", "r")

data = [Link]()

print(data[1])

[Link]()

(prints: We work with full zest.)

34. try-except-finally:

try:

x = 10/0

except ZeroDivisionError:

print("Cannot divide by zero")

finally:

print("This always executes")

35. Using pickle to write/read [Link]:

import pickle

numbers = [10,20,30,40,50]

with open('[Link]','wb') as f:
[Link](numbers, f)

with open('[Link]','rb') as f:

nums = [Link](f)

print(nums)

SECTION E

36.

(a) Read marks and calculate average:

with open('[Link]') as f:

marks = [float([Link]()) for line in f if [Link]()]

avg = sum(marks)/len(marks)

print("Average =", avg)

(b) Append new marks:

with open('[Link]','a') as f:

[Link]("\n85") # example

37.

def Push_student(records, StudentInfo):

for rec in records:

name, marks, subj = rec[0], rec[1], rec[2]

if subj == "Science":

[Link]([name, marks])

def Pop_student(StudentInfo):

while StudentInfo:
item = [Link]()

print(item)

print("Empty Stack")

--------------------------------------------------------------------

Note: The key above gives succinct answers and sample code for long questions.

If you would like a fully worked solution (line-by-line code outputs for every long question),

I can add them into the document as well.

Common questions

Powered by AI

An exception in Python refers to an event that disrupts the normal flow of instructions during program execution. For example, a ZeroDivisionError occurs when a division by zero is attempted. Proper handling can be achieved using 'try-except', such as: ``` try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") finally: print("This always executes") ``` In this scenario, the ZeroDivisionError is caught by the 'except' block, preventing the program from crashing and allowing a fallback message to be displayed, with 'finally' ensuring that the cleanup code runs regardless of the exception .

The 'pickle' module in Python is used for serializing and deserializing Python object structures, enabling saving Python objects into files and restoring them later. Serialization converts objects to a byte stream, suitable for writing to files, and deserialization reads the byte stream, reconstructing the original object. For example, to store a list of numbers, you can use: ``` import pickle numbers = [10,20,30,40,50] with open('numbers.dat','wb') as f: pickle.dump(numbers, f) with open('numbers.dat','rb') as f: nums = pickle.load(f) print(nums) ``` This code demonstrates writing a list to a file and reading it back, preserving the list structure .

The 'try-except-finally' construct is significant in Python for handling exceptions and ensuring that cleanup actions are performed regardless of an error occurrence. The 'try' block contains code that might cause an error, the 'except' block handles specific exceptions, and the 'finally' block contains code that will execute no matter the outcome, such as releasing resources. This ensures robust error management in code. For example, operations like file handling often use this construct to ensure files are closed properly even if an exception occurs .

A stack overflow occurs in data structures when a stack exceeds its capacity due to excessive 'PUSH' operations without adequate 'POP' operations to balance the addition of items. This results in an error due to lack of space to accommodate new elements. In contrast, regular stack operations like 'PUSH' simply add an item to the top of the stack, and 'POP' removes the top item and returns it. These operations are typically managed within the stack's size constraints, preventing overflow from occurring unless abused, as with continuous unchecked 'PUSH' actions . Stack overflow is more common in recursive programming due to excessive function calls without adequate base condition or termination control, unlike regular operations which are bounded by logical management .

In Python, the 'insert()' method allows inserting an element at a specified position in a list. It modifies the list in-place, adding the element without replacing other elements. For instance, using `L1.insert(2, 200)` on a list `L1` inserts 200 at index 2, shifting subsequent elements one position to the right . This method is particularly useful for precise placement of elements within a list, such as inserting new data into a sorted list while maintaining order or updating lists derived from input sequences .

Python implicitly converts data types during operations when it automatically handles type conversions to match the operation requirements, for example, converting integers to floats in arithmetic operations like '3 + 2.5', resulting in a float: 5.5 . In contrast, explicit type conversion requires the programmer to manually convert types using functions like int(), float(), or str(), such as converting a string '12' to an integer using 'int("12")'. Implicit conversion helps prevent some type errors by handling conversions smoothly, whereas explicit conversion offers greater control over the data types used in an operation .

In Python, function parameters are the variables listed in a function's definition that specify what kind of arguments it can accept. Arguments, on the other hand, are the actual values passed to a function when it is called . Python functions can indeed return multiple values by returning a tuple, which is accomplished using syntax like 'return a, b'. This allows for greater flexibility in functions, enabling them to output multiple results or values through tuple unpacking upon the function's completion .

'break' and 'continue' are control statements in Python loops, but they function differently. The 'break' statement terminates the current loop entirely, stopping further iterations and exiting the loop block. In contrast, the 'continue' statement skips the rest of the code inside the loop for the current iteration and proceeds to the next iteration. For example: ``` # Using break: for i in range(5): if i == 3: break print(i) # Output: 0 1 2 # Using continue: for i in range(5): if i == 3: continue print(i) # Output: 0 1 2 4 ``` In the 'break' example, the loop exits entirely when `i` equals 3. In the 'continue' example, the loop skips the print statement when `i` is 3, continuing with the next iteration .

'readlines()' and 'read()' are both file handling methods in Python, with distinct roles. 'readlines()' reads all lines in a file and returns them as a list, which is useful when you need to process lines individually or access the file content as a list . On the other hand, 'read()' reads the whole file into a single string, which can be beneficial when the entire content is required as a continuous block of text. The choice between the two depends on whether line-by-line processing is needed ('readlines()') or single-string processing suffices ('read()').

The 'w+' mode in the 'open()' function opens a file for both writing and reading. It signifies that the file is writable and readable, but it also truncates the file to zero length first, which deletes existing content . This mode can be useful in scenarios where it is necessary to rewrite the entire file content or when starting with a new file where both reading from and writing to the file will occur. Unlike 'r+' which allows reading and writing without truncating, or 'a+' which allows appending and reading without truncating, 'w+' is utilized when restarting content from scratch is required .

You might also like