0% found this document useful (0 votes)
11 views5 pages

Python Computer Science Test Answers

The document is an answer key for a Computer Science (Python) test paper, containing answers to various questions across multiple sections. It includes code snippets for file handling, database operations, and data manipulation using Python. The answers cover topics such as CSV, stacks, and the use of libraries like pickle and mysql.connector.

Uploaded by

reshmi
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)
11 views5 pages

Python Computer Science Test Answers

The document is an answer key for a Computer Science (Python) test paper, containing answers to various questions across multiple sections. It includes code snippets for file handling, database operations, and data manipulation using Python. The answers cover topics such as CSV, stacks, and the use of libraries like pickle and mysql.connector.

Uploaded by

reshmi
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

Answer Key – Computer Science (Python) Test Paper

Section A – Answers
1. rb, wb (also ab, rb+, wb+, ab+).

2. Comma (`,`).

3. Done

4. Stack.

5. DESCRIBE table_name;

6. (a) Comma Separated Values, (b) Database Management System.

Section B – Answers
7. Similarity: Both store data for later use.
Difference: CSV is human-readable, binary is not.

8. ```python
import csv
with open('[Link]', 'r') as f:
reader = [Link](f)
for i, row in enumerate(reader):
if i < 3:
print(row)
```

9. [5, 10, 15, 25]

10. ```python
import [Link]
mydb = [Link](host='localhost', user='root', password='1234',
database='school')
```

11. Advantage: Faster and compact storage.


Disadvantage: Not human-readable.

12. (a) csv (b) [Link]

Section C – Answers
13. ```python
import pickle
f = open('[Link]', 'wb')
for i in range(5):
empno = int(input('EmpNo: '))
name = input('Name: ')
sal = float(input('Salary: '))
[Link]([empno, name, sal], f)
[Link]()
```

14. ```python
def Push(Stack, item):
[Link](item)

def Pop(Stack):
if Stack:
return [Link]()
else:
return None
```

15. ```python
import csv
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
if int(row['Science']) > 80:
print(row['Name'])
```

16. (a) CREATE TABLE Books(BookID INT, Title VARCHAR(50), Price FLOAT);
(b) INSERT INTO Books VALUES(1, 'Python', 550);
(c) SELECT * FROM Books;

17. After [Link](12) → [12]


After [Link](34) → [12, 34]
After [Link](56) → [12, 34, 56]
After [Link]() → [12, 34]
After [Link](78) → [12, 34, 78]

18. ```python
import pickle
f = open('[Link]', 'rb')
try:
while True:
print([Link](f))
except EOFError:
[Link]()
```

Section D – Answers
19. ```python
import csv
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
for i in range(10):
pid = int(input('ProductID: '))
name = input('Name: ')
price = float(input('Price: '))
[Link]([pid, name, price])

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


reader = [Link](f)
for row in reader:
if float(row[2]) > 500:
print(row)
```

20. ```python
def push(stack):
item = input('Enter item: ')
[Link](item)

def pop(stack):
if stack:
print('Popped:', [Link]())
else:
print('Stack Empty')

def display(stack):
print(stack)

stack = []
while True:
ch = input('[Link] [Link] [Link] [Link]: ')
if ch == '1': push(stack)
elif ch == '2': pop(stack)
elif ch == '3': display(stack)
else: break
```
21. ```python
import [Link]
mydb = [Link](host='localhost', user='root', password='',
database='school')
cursor = [Link]()
[Link]('CREATE TABLE Student(RollNo INT, Name VARCHAR(30), Marks INT)')
[Link]("INSERT INTO Student VALUES(1, 'Amit', 85)")
[Link]("INSERT INTO Student VALUES(2, 'Ria', 90)")
[Link]()
[Link]('SELECT * FROM Student')
for row in [Link]():
print(row)
```

22. ```python
import pickle
name = input('Enter player name: ')
records = []
with open('[Link]', 'rb') as f:
try:
while True:
rec = [Link](f)
if rec[0] == name:
rec[1] += 500
[Link](rec)
except EOFError:
pass
with open('[Link]', 'wb') as f:
for rec in records:
[Link](rec, f)
```

23. ```python
import csv
total = 0
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
total += float(row[1])
print('Total Sales:', total)
```
Section E – Answers
```python
import pickle
f = open('[Link]', 'wb')
for i in range(5):
empid = int(input('EmpID: '))
name = input('Name: ')
dept = input('Department: ')
sal = float(input('Salary: '))
[Link]([empid, name, dept, sal], f)
[Link]()

f = open('[Link]', 'rb')
try:
while True:
rec = [Link](f)
if rec[2].lower() == 'hr':
print(rec)
except EOFError:
[Link]()
```

Common questions

Powered by AI

The logic for updating a player's score involves reading the records from a binary file, modifying the score if a condition is met, and writing the records back. Here is an example: ```python import pickle name = input('Enter player name: ') records = [] with open('player.dat', 'rb') as f: try: while True: rec = pickle.load(f) if rec[0] == name: rec[1] += 500 records.append(rec) except EOFError: pass with open('player.dat', 'wb') as f: for rec in records: pickle.dump(rec, f) ``` This script increases a player's score by 500 if the name matches the input. It first reads all records and updates them in-memory, then writes the modified records back, ensuring accurate data handling and minimal I/O operations.

To define a new database table for storing book information, you can use the following SQL statement: `CREATE TABLE Books(BookID INT, Title VARCHAR(50), Price FLOAT);` To insert data into this table once it is created, use an `INSERT INTO` statement: `INSERT INTO Books VALUES(1, 'Python', 550);`. This command inserts a book with Book ID 1, Title 'Python', and Price 550.

Here is an algorithm for a simple interactive stack application in Python: 1. Initialize an empty list `stack`. 2. Define a function `push(stack)` to append an item from user input. 3. Define a function `pop(stack)` to remove and print the top item if the stack is not empty; otherwise, print 'Stack Empty'. 4. Define `display(stack)` to print the current stack contents. 5. Create a loop to prompt user actions and call the respective functions based on user choice. Example code: ```python def push(stack): item = input('Enter item: ') stack.append(item) def pop(stack): if stack: print('Popped:', stack.pop()) else: print('Stack Empty') def display(stack): print(stack) stack = [] while True: ch = input('1.Push 2.Pop 3.Display 4.Exit: ') if ch == '1': push(stack) elif ch == '2': pop(stack) elif ch == '3': display(stack) else: break ``` This application allows users to interactively manage the stack using push, pop, and view operations, providing feedback based on the operation performed.

To implement a stack data structure in Python, you can use a list to hold the stack's elements and define functions for `push` and `pop` operations: ```python def Push(Stack, item): Stack.append(item) def Pop(Stack): if Stack: return Stack.pop() else: return None ``` When designing this code, consider edge cases such as popping from an empty stack, which should return `None` rather than cause an error. Efficiently implementing these operations ensures that the stack operates in constant time for both push and pop.

To implement Python code for creating, populating, and retrieving data from a MySQL table, use `mysql.connector`. First, establish a connection and create a table: ```python import mysql.connector mydb = mysql.connector.connect(host='localhost', user='root', password='', database='school') cursor = mydb.cursor() cursor.execute('CREATE TABLE Student(RollNo INT, Name VARCHAR(30), Marks INT)') ``` Next, insert data: ```python cursor.execute("INSERT INTO Student VALUES(1, 'Amit', 85)") cursor.execute("INSERT INTO Student VALUES(2, 'Ria', 90)") mydb.commit() ``` Finally, retrieve and print data: ```python cursor.execute('SELECT * FROM Student') for row in cursor.fetchall(): print(row) ``` Error handling: Use try-except blocks to catch and handle errors such as `mysql.connector.Error` for better robustness. This includes handling connection failures, incorrect SQL queries, or data type mismatches, ensuring the application fails gracefully and provides meaningful error messages.

To connect to a MySQL database using the `mysql.connector` package, use the following command: ```python import mysql.connector mydb = mysql.connector.connect(host='localhost', user='root', password='1234', database='school') ``` The `host` parameter specifies the database server's address, `user` indicates the username with access to the database, `password` is the password for the user, and `database` specifies the name of the database you want to connect to. Each parameter is crucial for ensuring a secure and successful database connection.

To open and read specific entries from a CSV file in Python, you can use the `csv` module to open the file and a loop to iterate through the rows. For example: ```python import csv with open('students.csv', 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i < 3: print(row) ``` This snippet reads the file 'students.csv' and prints only the first three rows using a loop with enumeration.

The `pickle` module can be used to serialize and deserialize data in Python. Serialization writes data to a file, and deserialization reads it back. For example: ```python import pickle f = open('emp.dat', 'wb') for i in range(5): empno = int(input('EmpNo: ')) name = input('Name: ') sal = float(input('Salary: ')) pickle.dump([empno, name, sal], f) f.close() ``` To read back: ```python import pickle f = open('emp.dat', 'rb') try: while True: print(pickle.load(f)) except EOFError: f.close() ``` This application writes employee numbers, names, and salaries to 'emp.dat' and reads them back. Consider handling the `EOFError` during reading to stop iterating when the end of the file is reached.

To aggregate and display total sales from a CSV file in Python, you can use a loop to iterate over the CSV rows and sum up the sales values. For example: ```python import csv total = 0 with open('sales.csv', 'r') as f: reader = csv.reader(f) for row in reader: total += float(row[1]) print('Total Sales:', total) ``` This code opens 'sales.csv', reads through each row, and adds the second element (assumed to be the sales amount) to the total, displaying the total sales at the end.

The key difference between CSV and binary formats is that CSV files are human-readable while binary files are not. CSVs can be easily opened and edited with text editors, making it accessible for users who need to view or manually edit the data. However, CSV files are generally slower to read and write due to their text nature. Binary files provide faster and more compact storage, which makes them efficient for large volume data handling and computation. The disadvantage of binary is the lack of human readability which makes debugging more difficult.

You might also like