0% found this document useful (0 votes)
25 views9 pages

Pre 1 Cs Ans

The document covers various programming concepts, including Python code predictions, SQL queries, and file operations. It explains compile-time vs runtime errors, string manipulations, and database interactions. Additionally, it discusses networking topologies and provides examples of functions for managing data in CSV and binary files.

Uploaded by

moammed
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)
25 views9 pages

Pre 1 Cs Ans

The document covers various programming concepts, including Python code predictions, SQL queries, and file operations. It explains compile-time vs runtime errors, string manipulations, and database interactions. Additionally, it discusses networking topologies and provides examples of functions for managing data in CSV and binary files.

Uploaded by

moammed
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/ 9

1.

Predict the output of the Python code:

python
CopyEdit
List1 = list("Examination")
List2 = List1[1:-1]
new_list = []
for i in List2:
j = List2.index(i)
if j % 2 == 0:
List1.remove(i)
print(List1)

Answer:
['E', 'x', 'm', 'i', 'n', 'a', 't', 'i', 'n']
Explanation:
List1.remove(i) modifies List1, removing elements from it based on their positions in
List2. This removal happens only for indices in List2 where j % 2 == 0.

2. Difference between compile-time and runtime error:


o Compile-Time Error: Errors detected by the interpreter before the code is
executed. Examples: Syntax errors, indentation errors.
o Runtime Error: Errors that occur during the execution of the program.
Examples: Division by zero, accessing an invalid index.

3. Output of the string operation:

myexam = "@@PREBOARDEXAMINATION2025@@"
print(myexam[::-2])

Answer:
'@502NAIETRAEP@'
Explanation: The slice [::-2] traverses the string in reverse, skipping every other
character.

4. Output of the dictionary operation:

my_dict = {"name": "Aman", "age": 26}


my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items())

Answer:
dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])
5. Find the correct outputs and max/min values of Y:

import random
X = random.random()
Y = random.randint(0, 4)
print(int(X), ":", Y + int(X))

Answer:

o Correct Outputs:
 A) 0:0
 D) 0:3
o Maximum Value for Y: 4
o Minimum Value for Y: 0

6. Correct the code to check for prime numbers:

def prime():
n = int(input("Enter number to check: "))
for i in range(2, n // 2 + 1):
if n % i == 0:
print("Number is not prime\n")
break
else:
print("Number is prime\n")

Corrections Made:

o Added a closing parenthesis in int(input(...)).


o Corrected range(2, n//2) to range(2, n//2 + 1) for inclusive checking.
o Replaced if n % i = 0: with if n % i == 0:.
o Fixed the quotation mark for the last print.

SQL Questions

1. SQL command to see the list of tables:


Answer:

SHOW TABLES;

2. SQL command to insert a new record:


Answer:
INSERT INTO table_name (column1, column2, ...) VALUES (value1,
value2, ...);

3. Constraints on table columns:


o (A) To disallow NULL but allow duplicates:
Answer: NOT NULL
o (B) To disallow duplicates but allow NULL:
Answer: UNIQUE

Miscellaneous Questions

1. Full forms of POP and HTTPS:


o POP: Post Office Protocol
o HTTPS: HyperText Transfer Protocol Secure
2. Protocols used for specific tasks:
o Remote Login: Telnet or SSH
o File Transferring: FTP (File Transfer Protoco

1. Method SHOWLINES()
def SHOWLINES():
with open("EXAMCS.txt", "r") as file:
lines = file.readlines()
for line in lines:
if 'ke' not in line:
print(line.strip())

# Example Output:
# We all pray for everyone’s safety.

2. Function RainCount()
def RainCount():
with open("RAIN.txt", "r") as file:
content = file.read().lower() # Convert to lowercase for case-
insensitive search
count = content.count("rain")
print(f"Rain – {count}")

# Example Output:
# Rain – 2

3. Stack Operations
(i) Push_element()
def Push_element(stack, customers):
for customer in customers:
if customer[2].lower() == "goa":
stack.append((customer[0], customer[1]))

(ii) Pop_element()
def Pop_element(stack):
while stack:
print(stack.pop())
print("Stack Empty")

Example Usage:

customers = [["John", "1234567890", "Goa"], ["Alice", "9876543210", "Delhi"],


["Bob", "5678901234", "Goa"]]
stack = []
Push_element(stack, customers)
Pop_element(stack)

Output:

('Bob', '5678901234')
('John', '1234567890')
Stack Empty

4. Function to Push Stationery Items


def Push(SItem):
stack = []
count = 0
for name, price in SItem.items():
if price > 75:
stack.append(name)
count += 1
print(" ".join(stack))
print(f"The count of elements in the stack is {count}")

# Example Usage:
Ditem = {"Pen": 106, "Pencil": 59, "Notebook": 80, "Eraser": 25}
Push(Ditem)

# Output:
# Notebook Pen
# The count of elements in the stack is 2

5. Predict the Output

(a) Code 1
s = "All The Best"
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)

Output:

ALLthe bBes#

(b) Code 2
F1 = "WoNdERFUL"
F2 = "StuDenTS"
F3 = ""
for I in range(0, len(F2) + 1):
if F1[I] >= 'A' and F1[I] <= 'F':
F3 = F3 + F1[I]
elif F1[I] >= 'N' and F1[I] <= 'Z':
F3 = F3 + F2[I]
else:
F3 = F3 + "*"
print(F3)

Output:
The code contains an error: IndexError occurs when I exceeds the length of F1. The loop
condition should be range(len(F2)) instead of len(F2)+1.

Corrected Output (if fixed):

W**

Part A) Write SQL Queries

1. To display the details of the courses with names starting with ‘D’:

SELECT * FROM TECH_COURSE WHERE CNAME LIKE 'D%';

2. To display the fees of courses in descending order:

SELECT FEES FROM TECH_COURSE ORDER BY FEES DESC;


3. To display the sum of fees of all courses for which TID is not null:

SELECT SUM(FEES) FROM TECH_COURSE WHERE TID IS NOT NULL;

4. To display the course name with fees less than 15000:

SELECT CNAME FROM TECH_COURSE WHERE FEES < 15000;

Part B) Write Outputs

1. SELECT DISTINCT TID FROM TECH_COURSE;


Output: Displays all unique TIDs from the table.
2. SELECT TID, COUNT(*), MIN(FEES) FROM TECH_COURSE GROUP BY TID HAVING
COUNT(TID) > 1;
Output: For each TID with more than one occurrence, it shows TID, the number of
occurrences, and the minimum fees.
3. SELECT CNAME FROM TECH_COURSE WHERE FEES > 15000 ORDER BY CNAME;
Output: Displays all course names with fees greater than 15000, sorted alphabetically by
course name.
4. SELECT AVG(FEES) FROM TECH_COURSE WHERE FEES BETWEEN 15000 AND 17000;
Output: Displays the average fees for courses where fees are between 15000 and 17000.

Python Program: CSV Operations

(a) ADD Function


import csv

def ADD():
with open('record.csv', mode='a', newline='') as file:
writer = csv.writer(file)
empid = input("Enter Employee ID: ")
name = input("Enter Employee Name: ")
mobile = input("Enter Employee Mobile: ")
writer.writerow([empid, name, mobile])
print("Record added successfully.")

(b) COUNTR Function


def COUNTR():
count = 0
with open('record.csv', mode='r') as file:
reader = csv.reader(file)
for row in reader:
count += 1
print(f"Number of records: {count}")
Database Table: Fees

1. Primary Key:
The best attribute to be declared as a primary key is Roll no.
2. Degree of the Table:
Degree = Number of attributes = 5.
3. Insert Data into the Table:

sql
CopyEdit
INSERT INTO Fees (Rollno, Name, Class, Fees, Qtr)
VALUES (1, 'Arjun', '10th', 2500, 1),
(2, 'Meera', '9th', 2300, 2),
(3, 'Ravi', '8th', 2400, 3),
(4, 'Anita', '10th', 2500, 4);

4. To Remove the Table Fees:


Command:

sql
CopyEdit
DROP TABLE Fees;

5. To Display Table Structure:

sql
CopyEdit
DESCRIBE Fees;

Python Function: DataDisplay()


python
CopyEdit
import mysql.connector

def DataDisplay():
try:
# Establish database connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="tiger",
database="school"
)
cursor = conn.cursor()

# Input and insert student details


roll_no = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
class_ = int(input("Enter Class: "))
marks = int(input("Enter Marks: "))
cursor.execute(
"INSERT INTO student (RollNo, Name, Class, Marks) VALUES (%s, %s,
%s, %s)",
(roll_no, name, class_, marks)
)
conn.commit()

# Retrieve and display students with marks > 75


cursor.execute("SELECT * FROM student WHERE Marks > 75")
results = cursor.fetchall()
for row in results:
print(row)

except mysql.connector.Error as err:


print(f"Error: {err}")
finally:
cursor.close()
conn.close()

Part 1: Binary File Operations

i. Function to Create and Add Data to Book.dat:

python
CopyEdit
import pickle

def CreateFile():
with open("Book.dat", "ab") as file: # Open the file in append-binary
mode
while True:
BookNo = int(input("Enter Book Number: "))
Book_Name = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
record = [BookNo, Book_Name, Author, Price]
pickle.dump(record, file) # Write the record to the binary file
choice = input("Do you want to add another record? (yes/no): ")
if choice.lower() != 'yes':
break
print("Data added to Book.dat successfully.")

ii. Function to Count Records by Author in Book.dat:

python
CopyEdit
def CountRec(author_name):
count = 0
try:
with open("Book.dat", "rb") as file: # Open the file in read-binary
mode
while True:
try:
record = pickle.load(file) # Load each record
if record[2].lower() == author_name.lower(): # Check
author name
count += 1
except EOFError: # End of file reached
break
except FileNotFoundError:
print("Book.dat not found.")
return count

# Example Usage:
author = input("Enter the author's name to search: ")
print(f"Number of books by {author}: {CountRec(author)}")

Part 2: Pandas Infosystem Networking

1. (a) Most Appropriate Topology with an Advantage:


Suggested Topology: Star Topology
Advantage: If one connection fails, it does not affect the other connections.
2. (b) Cable Layout Suggestion:
Connect each building directly to the Administrative Office (Central Node) using
individual cables.

Example Layout:

Building 1 ─────┐

Building 2 ─────┤

Building 3 ─────┤─── Administrative Office

Building 4 ─────┘

3. (c) Suitable Place for the Server:


Suggested Place: Administrative Office
Reason: It is centrally located, which minimizes the average distance between the server
and other buildings, reducing latency and cost.
4. (d) Device to Connect Computers in Each Building:
Device: Switch
5. (e) Protocol for Face-to-Face Calling:
Suggested Protocol: VoIP (Voice over Internet Protocol)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy