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

12 CS Set B Anskey

The document is an answer key for the Pre-Board Examination in Computer Science for Class XII at Vidya Jain Public School, detailing questions and answers across various sections. It includes multiple-choice questions, programming tasks, SQL queries, and explanations for Python code. The document serves as a guide for evaluating students' understanding of computer science concepts and programming skills.

Uploaded by

msindiatravel
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)
19 views12 pages

12 CS Set B Anskey

The document is an answer key for the Pre-Board Examination in Computer Science for Class XII at Vidya Jain Public School, detailing questions and answers across various sections. It includes multiple-choice questions, programming tasks, SQL queries, and explanations for Python code. The document serves as a guide for evaluating students' understanding of computer science concepts and programming skills.

Uploaded by

msindiatravel
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
You are on page 1/ 12

SET- B

VIDYA JAIN PUBLIC SCHOOL, ROHINI, NEW DELHI


PRE-BOARD EXAMINATION - 1 (2024-25)
ANSWER KEY
SUBJECT – COMPUTER SCIENCE (083)
CLASS –XII
Duration : 3 Hours M.M.:70

Q. Details of the questions Mark(s)


SECTION A
Q.1 a.Eval 1
Q.2 b. NameError 1
Q.3 d. NONE 1
Q.4 a. total 1
Q.5 d. Explicit type casting 1
Q.6 c. Adds multiple elements at last 1
Q.7 a.4 1
Q.8 a. Start_game() 1
Q.9 a. Beginning of file 1
Q.10 b. myfile.read() 1
Q.11 c. 100+200 1
Q.12 d.Database Management System 1
Q.13 C.SELECT * FROM Persons WHERE FirstName LIKE ‘%a’ 1
Q.14 a. UPDATE 1
Q.15 c. Update 1
Q.16 d. = 1
Directions (Q.Nos. 17-18) Assertion and Reason based Questions.
Q.17 a. Both A and R are true and R is the correct explanation for A 1
Q.18 c.A is True but R is False 1
SECTION B
Q.19 Let's analyze the table provided: 2

### a. Degree and Cardinality of the ORDERS table

1. **Degree:** The degree of a table is the number of columns it contains.


- The ORDERS table has the following columns:
- ORDER_ID
- CUSTOMER_NAME
- PRODUCT_ID
- QUANTITY
- ORDER_DATE
- Therefore, the **degree** of the ORDERS table is **5**.

2. **Cardinality:** The cardinality of a table refers to the number of rows (or records) in the
table.
- The ORDERS table contains the following records:
- 101
- 102
- 103
- 104
- Therefore, the **cardinality** of the ORDERS table is **4**.
### b. Identify the Column which can serve as a primary key
A primary key is a column (or a combination of columns) in a database table that uniquely
identifies each row in that table. The primary key must contain unique values and cannot
contain NULL values.
Q.20 Let's analyze the provided Python code step by step. 2

```python
def modifyList(x):
x.append(sum(x))
print(x, end=' ')

L = [1, 2, 3, 4]
print(L)
modifyList(L)
The code defines a function `modifyList(x)` that takes a
list `x` as an argument. Inside the function:
- `x.append(sum(x))` calculates the sum of the current
elements in the list `x` and appends this sum to the list.
- `print(x, end=' ')` prints the modified list `x` followed
by a space (instead of a newline).
2. The list `L` is initialized with the values `[1, 2, 3, 4]`.
3. The first `print(L)` statement outputs the initial list:
```
[1, 2, 3, 4]
4. The `modifyList(L)` function is then called, passing the
list `L`:
- Inside `modifyList`, `sum(x)` is calculated. The sum of
`1 + 2 + 3 + 4` equals `10`.
- `10` is appended to the list `L`, which now changes `L`
to `[1, 2, 3, 4, 10]`.
- The modified list is printed, resulting in:
```
[1, 2, 3, 4, 10]
Q.21 The provided Python code contains several syntax errors and a misuse of function 2
parameters. Let's identify and correct the errors step by step.

### Errors in the Original Code:


1. **Improper case for function definition:** The keyword `DEF` should be lowercase
(`def`).
2. **Improper use of parentheses and colon:** The function body should have a colon (`:`)
after the parameter list, and it should also be indented properly.
3. **Incorrect syntax for the `print` function:** The `end` parameter should use `=` instead
of `:`, and the quotes around the string should be single or double quotes correctly.
4. **Incorrect order of arguments in the function call:** When calling a function with
keyword arguments, the keyword arguments should come after positional arguments or be
specified in the correct order.
5. **The call to `say` is incorrect:** The arguments are provided incorrectly and should be
adjusted.

### Corrected Code:


Here’s the corrected version of the provided code with the necessary fixes highlighted:

```python
def say(message, times=1): # Corrected DEF to def and added colon
print(message * times, end=' ') # Corrected the print statement

say('Hello and', times=10) # Correct order of arguments


say('World') # This is fine
Q.22 Let's analyze the provided code step by step. 2

Here's the code you've provided:

```python
def Changer(P, Q=10):
P=P/Q
Q=P%Q
return P

A = 200
B = 20
A = Changer(A, B)
print(A, B)
B = Changer(B)
print(A, B)
```

### Breakdown of Execution:

1. **Function Definition:** The function `Changer` takes two parameters, `P` and `Q`, with
`Q` having a default value of 10. Inside the function:
- `P` is divided by `Q`, and the result is assigned back to `P`.
- `Q` is reassigned to the remainder of `P` divided by `Q`.
- The function returns the modified value of `P`.

2. **Initialization:**
- `A` is initialized to `200`.
- `B` is initialized to `20`.
3. **First Function Call:**
- `A = Changer(A, B)` translates to `A = Changer(200, 20)`.
- Inside `Changer(200, 20)`:
- `P` becomes `200 / 20 = 10.0`.
- `Q` is then updated to `10.0 % 20`, which is `10.0` (since 10.0 is less than 20).
- `Changer` returns `10.0`, so now `A` is `10.0`.
- The first `print(A, B)` outputs:
```
10.0 20
```

4. **Second Function Call:**


- `B = Changer(B)` translates to `B = Changer(20)`, where `Q` defaults to `10`.
- Inside `Changer(20)`:
- `P` becomes `20 / 10 = 2.0`.
- `Q` gets updated to `2.0 % 10`, which is still `2.0`.
- `Changer` returns `2.0`, so now `B` is `2.0`.
- The second `print(A, B)` outputs:
```
10.0 2.0
Q.23 Let's break down the SQL statements you provided, and predict their outputs. 2

### a. `select pow(2,3)`

The `POW` (or `POWER`) function in SQL raises the first argument to the power of the second
argument. In this case, you are raising \(2\) to the power of \(3\):

\[
2^3 = 8
\]

**Output of a:**
8
### b. `select round(342.92,1)`

The `ROUND` function in SQL rounds a numeric value to a specified number of decimal places. In this
instance, you are rounding \(342.92\) to \(1\) decimal place:

- \(342.92\) rounded to one decimal place becomes \(342.9\) (since the digit after the first decimal
place is \(2\), which does not round up).

**Output of b:**
Q.24 Certainly! Below is a Python function named `countbb()` that reads from a text file named 2
`article.txt`, counts the occurrences of the words "bat" and "ball" (in a case-insensitive manner), and
then displays the counts.

```python
def countbb():
# Initialize counters for 'bat' and 'ball'
count_bat = 0
count_ball = 0

try:
# Open the file in read mode
with open('article.txt', 'r') as file:
# Read the content of the file
content = file.read()

# Convert to lowercase to ensure case-insensitive comparison


content_lower = content.lower()

# Count occurrences of 'bat' and 'ball'


count_bat = content_lower.count('bat')
count_ball = content_lower.count('ball')

# Display the results


print(f"Number of times bat occurs is {count_bat}")
print(f"Number of times ball occurs is {count_ball}")

except FileNotFoundError:
print("The file 'article.txt' was not found.")
except Exception as e:
print(f"An error occurred: {e}")

# Call the function


countbb()
Q.25 Here are the SQL queries for the given situations based on the provided `Club` table 2
structure:

### a. Sort the salaries of coaches in descending order by their pay.

```sql
SELECT CoachID, CoachName, Pay
FROM Club
ORDER BY Pay DESC;
```

### b. Update the "Pay" of Coach "KUKREJA" to 1100.

```sql
UPDATE Club
SET Pay = 1100
WHERE CoachName = 'KUKREJA';
```

### c. Delete the records of coaches who coach "SWIMMING".

```sql
DELETE FROM Club
WHERE Sports = 'SWIMMING';
```

### d. Display the coaches who coach Karate, ordered by age in ascending order.
```sql
SELECT CoachID, CoachName, Age
FROM Club
WHERE Sports = 'KARATE'
ORDER BY Age ASC;
"KUKREJA" in the `Club` table.
SECTION C
Q.26 You can achieve this by defining the function `SumDiv(L, x)` that iterates through the list `L`, checks if 3
each element is divisible by either `x` or `x + 1`, and sums the qualifying elements. Here’s how you
can implement this function in Python:

```python
def SumDiv(L, x):
# Initialize the sum
total_sum = 0

# Iterate through each element in the list


for num in L:
# Check if the number is divisible by x or x + 1
if num % x == 0 or num % (x + 1) == 0:
total_sum += num

return total_sum

# Example usage
L = [10, 27, 12, 20, 22]
x=5
result = SumDiv(L, x)
print(result) # Output: 42
### Explanation:
1. **Initialization**: The variable `total_sum` is initialized to zero to store the cumulative sum of the
qualifying numbers.
2. **Iteration**: The function iterates over each integer in the list `L`.
3. **Divisibility Check**: Inside the loop, it checks if the current number `num` is divisible by `x`
(`num % x == 0`) or `x + 1` (`num % (x + 1) == 0`).
4. **Summation**: If either condition is true, the number is added to `total_sum`.
5. **Return Value**: Finally, the function returns the computed `total_sum`.
Q.27 Let's go through each of the queries and tasks you've mentioned: 3

### a. Identify the attribute best suitable to be declared as a primary key for the 'Employee'
table.
The attribute that is best suitable to be declared as a primary key for the 'Employee' table is
**Employee_ID**.

**Rationale**:
- A primary key must uniquely identify each record in the table. The `Employee_ID` attribute
is likely designed to be a unique identifier for each employee and would meet the
requirements for a primary key by ensuring that no two employees have the same
`Employee_ID`.

### b. Write an appropriate SQL query to modify the column size of 'First_Name' from 15
characters to 30 characters.

To modify the column size of `First_Name` from 15 characters to 30 characters, you can use
the following SQL `ALTER TABLE` statement:

```sql
ALTER TABLE Employee
MODIFY First_Name CHAR(30);
```

**Note**: The exact syntax may vary slightly depending on the database system you are
using (e.g., MySQL, Oracle, SQL Server, etc. In some systems, you may use `VARCHAR`
instead of `CHAR`, and the keyword `MODIFY` may be different, such as `ALTER COLUMN` in
SQL Server).

### c. The department wants to clear all the data from the 'Employee' table but keep the
table structure intact. Which SQL command should they use from the following options?

The correct option to clear all the data from the `Employee` table while keeping the table
structure intact is:

**iv. TRUNCATE TABLE Employee**


Q.28 Certainly! Below is a Python function that counts the number of occurrences of the word "My" in a 3
text file named `STORY.TXT`. The function reads the content of the file, processes it, and returns the
count of the word "My".

```python
def count_my_words_in_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()

# Split the content into words and count occurrences of "My"


words = content.split()
count_my = sum(1 for word in words if word == "My")

return count_my

except FileNotFoundError:
return "The file was not found."
# Usage
filename = "STORY.TXT"
result = count_my_words_in_file(filename)
print(f"Count of 'My' in file: {result}")
Q.29 Certainly! Here’s a concise summary of text files, binary files, and CSV files: 3

### Text File


A **text file** is a type of file that stores data in plain text format, which can be easily read
and edited by humans and machines alike. The data is encoded using character encoding
systems (like ASCII or UTF-8) and consists of lines of text. Text files typically have extensions
like `.txt`, `.csv`, or `.json`. Because they are human-readable, they are widely used for
storing simple data, scripts, logs, and configuration files. However, they are not suitable for
storing complex data structures or large amounts of binary data efficiently.

### Binary File


A **binary file** is a type of file that contains data in a format that is not intended to be
human-readable. This means the data is stored in binary format (0s and 1s), allowing for
efficient storage and processing of data types like images, audio, video, and executable files.
Examples of binary files include `.exe`, `.jpg`, `.bin`, and `.mp3`. While binary files are more
space-efficient and can represent complex data structures, they require specific software or
tools to read and interpret their contents, making them less flexible than text files for casual
human use.
Q.30 Sure! Below is a Python function that counts the number of lines starting with a digit in a text file 3
named `Diary.txt`. The function reads the content of the file, checks each line, and returns the count
of lines that begin with a digit.

```python
def count_lines_starting_with_digit(filename):
try:
with open(filename, 'r') as file:
# Initialize line count
count = 0

# Iterate through each line in the file


for line in file:
# Check if the line starts with a digit
if line and line[0].isdigit():
count += 1

return count

except FileNotFoundError:
return "The file was not found."
except Exception as e:
return f"An error occurred: {e}"

# Usage
filename = "Diary.txt"
result = count_lines_starting_with_digit(filename)
print(f"Number of lines starting with a digit in the file: {result}")
SECTION D
Q.31 LAN, MAN, WAN, and PAN are acronyms that refer to different types of networks, distinguished 4
primarily by their geographical coverage and intended use. Here's a brief overview of each:
### 1. LAN (Local Area Network)
- **Definition**: A LAN is a network that connects computers and devices within a limited
geographical area, such as a home, school, office, or building.
- **Characteristics**:
- Typically covers a small area, often within a few hundred meters.
- High data transfer rates (typically in the range of 100 Mbps to 10 Gbps).
- Commonly uses Ethernet or Wi-Fi technologies.
- Devices on a LAN can communicate directly with one another, facilitating resource sharing (such
as files and printers).

### 2. MAN (Metropolitan Area Network)


- **Definition**: A MAN is a network that covers a larger geographical area than a LAN but is smaller
than a WAN, typically encompassing a city or a large campus.
- **Characteristics**:
- Covers several kilometers, making it suitable for connecting multiple LANs within the same
metropolitan area.
- Data transfer rates can be higher than those of LANs and can vary based on technology.
- Often used to connect businesses, schools, and government facilities in a specific city to share
resources efficiently.

### 3. WAN (Wide Area Network)


- **Definition**: A WAN is a network that spans a large geographical area, potentially covering
countries or continents.
- **Characteristics**:
- Covers vast distances, ranging from hundreds to thousands of miles.
- Lower data transfer rates compared to LANs and MANs, depending on the technology used (such
as satellite, leased lines, VPNs, etc.).
- Utilizes public or private networks and can connect multiple LANs and MANs.
- The Internet is the largest and most well-known example of a WAN.

### 4. PAN (Personal Area Network)


- **Definition**: A PAN is a small network designed for personal devices, typically within a range of
a few meters to a short distance.
- **Characteristics**:
- Used to connect devices such as smartphones, tablets, laptops, and wearable technology.
- Data transfer rates can vary but are generally intended for low data volume (e.g., Bluetooth
connections).
- Often operates in a wireless format, such as Bluetooth or Zigbee, allowing for personal device
interconnection and communication.
Q.32 Certainly! Below is a Python program that defines a binary file structure for storing employee 4
records with fields: Employee ID (EID), Name (Ename), Designation, and Salary. The program
includes two functions: `CreateEmp()` for adding employee records to a binary file (`emp.dat`), and
`display()` for reading and displaying all employee records from the binary file.

### Python Code Implementation

```python
import struct
# Employee class to represent employee data
class Employee:
def __init__(self, eid, ename, designation, salary):
self.eid = eid
self.ename = ename
self.designation = designation
self.salary = salary

# Method to convert the Employee to a binary format


def to_binary(self):
return struct.pack('I20s20sf', self.eid, self.ename.encode('utf-8'), self.designation.encode('utf-
8'), self.salary)

@staticmethod
def from_binary(data):
unpacked_data = struct.unpack('I20s20sf', data)
return Employee(unpacked_data[0], unpacked_data[1].decode('utf-8').strip(b'\
x00').decode('utf-8'),
unpacked_data[2].decode('utf-8').strip(b'\x00').decode('utf-8'),
unpacked_data[3])

# Function to create and store employee record


def CreateEmp(filename="emp.dat"):
eid = int(input("Enter employee ID: "))
ename = input("Enter employee name: ")
designation = input("Enter designation: ")
salary = float(input("Enter salary: "))

employee = Employee(eid, ename, designation, salary)

# Append employee data to the binary file


with open(filename, 'ab') as file:
file.write(employee.to_binary())

print("Employee record added successfully.")


SECTION E
Q.33 A file is a collection of data or information that is stored on a storage device. Files can be of 5
different types, including text files, binary files, audio files, video files, images, and more.
Files are essential in computing for data storage, sharing, and manipulation.
**File Handling**:
File handling refers to the various operations that can be performed on files. This includes
actions such as:
- **Creating a file**: Making a new file in the specified directory.
- **Opening a file**: Accessing an existing file for reading or writing data.
- **Reading from a file**: Retrieving data from the file.
- **Writing to a file**: Saving or updating data in the file.
- **Closing a file**: Releasing the resources associated with the file once operations are
complete.
- **Deleting a file**: Removing the file from the storage.
In Python, files can be handled using built-in functions and libraries that allow you to
seamlessly perform these operations.
### ii. Python Program Code
Below is a Python program that uses two functions: `addBook()` to write book details into a
CSV file named `book.csv`, and `countRecords()` to count and display the total number of
records in the file. The program uses a tab (`\t`) as the separator when writing to the CSV
file.
```python
import csv
def addBook(filename="book.csv"):
book_no = input("Enter book number: ")
book_name = input("Enter book name: ")
no_of_pages = input("Enter number of pages: ")
# Open the CSV file in append mode
with open(filename, mode='a', newline='') as file:
writer = csv.writer(file, delimiter='\t') # Using tab as separator
writer.writerow([book_no, book_name, no_of_pages]) # Write the book details
print("Book record added successfully.")
Q.34 1. **Easy to Learn and Use**: 5
Python has a simple and clean syntax that is easy to read and write, making it an excellent
choice for beginners. The language promotes good programming practices and its
constructs are intuitive. This simplicity allows programmers to focus on solving problems
rather than syntactic complexities.
2. **Interpreted Language**:
Python is an interpreted language, meaning that the code is executed line-by-line at
runtime rather than being compiled into machine language. This feature allows for easier
debugging and testing, as developers can run their code in an interactive shell and see the
results immediately.
3. **Versatile and Multi-Paradigm**:
Python supports multiple programming paradigms, including procedural, object-oriented,
and functional programming. This flexibility allows developers to choose the approach that
best fits their project requirements. Python’s versatility also extends to its applications,
which range from web development to data analysis, machine learning, automation, and
more.
4. **Extensive Standard Library**:
Python comes with a large standard library that provides built-in modules and functions
for many tasks, such as regular expressions, file I/O, web services, and more. This allows
developers to leverage existing solutions rather than reinventing the wheel, speeding up
development time and improving productivity.
5. **Strong Community Support**:
Python has a robust and active community of developers who contribute to a wealth of
resources, including libraries, frameworks, and tools. This community support is beneficial
for newcomers and experienced developers alike, as it provides access to documentation,
tutorials, and troubleshooting advice.
### Database Management System (DBMS)
A Database Management System (DBMS) is software that facilitates the administration,
organization, and management of databases. It provides an interface between database
users and the databases themselves, allowing users to create, read, update, and delete data
while ensuring data integrity and security. DBMS systems are essential for handling large
amounts of data efficiently and securely across various applications.
Q.35 To help Aradhana complete her program for updating a binary file `student.dat`, let's address each 5
part of your question:

### I. Which module should be imported in the program? (Statement 1)


The program needs to work with pickling, which is a way to serialize and deserialize Python objects.
Therefore, Aradhana should import the `pickle` module.
```python
import pickle # STATEMENT 1
### II. Write the correct statement required to open a temporary file named temp.dat. (Statement
2)
The temporary file should be opened in write-binary mode. The correct mode for the `open`
function in this case would be `"wb"`.
```python
f2=open("temp.dat","wb") # Statement 2
```
### III. Which statement should Aradhana fill in Statement 3 to write the data to the binary file?
In Statement 3, when a record that matches the specified roll number is found, the updated student
information should be dumped back into the temporary file. The correct statement would be:
```python
pickle.dump(e, f2) # Statement 3
```
### IV. Statement 4 to rename temp.dat to student.dat?
For Statement 4, the `os` module should be used to rename the file. The correct function to use is
`os.rename()`, so the statement should be:

You might also like