State True or False:
"In a Python program, if a break statement is given in a nested loop, it terminates the execution of all loops in one go."
Answer
False
Reason — In a Python program, if a break statement is given in a nested loop, it only terminates the execution of the innermost loop where the break statement is encountered. It does not affect the outer loops or any remaining loops in the nested structure.
In a table in MYSQL database, an attribute A of datatype varchar(20) has the value "Keshav". The attribute B of datatype char(20) has value “Meenakshi”. How many characters are occupied by attribute A and attribute B ?
- 20, 6
- 6, 20
- 9, 6
- 6, 9
Answer
6, 20
Reason — The datatype VARCHAR(20) is a variable-length character string that can store up to 20 characters. When "Keshav" (6 characters) is assigned to attribute A with VARCHAR(20), it occupies only 6 characters of storage space because VARCHAR adjusts the space based on the actual data length. The datatype CHAR(20) is a fixed-length character string that always occupies the specified amount of space, in this case, 20 characters. When "Meenakshi" (9 characters) is assigned to attribute B with CHAR(20), it still occupies all 20 characters of storage space because CHAR pads the data with spaces to fill up the allocated space, even if the actual data is shorter.
What will be the output of the following statement:
print(3 - 2 ** 2 ** 3 + 99/11)
- 244
- 244.0
- -244.0
- Error
Answer
-244.0
Reason — In Python, both ** (exponentiation) and / (division) operators have the same level of precedence, which means they are evaluated from left to right if they appear together without parentheses. However, the exponentiation operator ** is right-associative, which means it is evaluated from right to left. In the given expression print(3 - 2 ** 2 ** 3 + 99 / 11)
, the innermost exponentiation (2 ** 3) is evaluated first, followed by the outer exponentiation (2 ** 8). Then subtracting the result of the exponentiation from 3, 3 − 256 = −253, then adding the result of the division ((99/11) = 9) to the previously calculated value −253 + 9 = −244.0. The expression is evaluated as follows:
3 - 2 ** 2 ** 3 + 99 / 11
= 3 - 2 ** 8 + 99 / 11
= 3 - 256 + 99 / 11
= 3 - 256 + 9.0
= -253 + 9.0
= -244.0
Select the correct output of the code:
s = "Python is fun"
l = s.split()
s_new = "-".join([l[0].upper(), l[1], l[2].capitalize()])
print(s_new)
- PYTHON-IS-Fun
- PYTHON-is-Fun
- Python-is-fun
- PYTHON-Is -Fun
Answer
PYTHON-is-Fun
Reason — The code initializes a string variable s
with the value 'Python is fun'. It splits the string into words using split() method, then converts the first word to uppercase ('PYTHON') using indexing and the upper() method, and capitalizes the third word ('Fun') with the capitalize() method. It then joins the modified words with a hyphen ('-') as the separator using the join() method and prints the result.
In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and another table, Beta has degree 3 and cardinality 5, what will be the degree and cardinality of the Cartesian product of Alpha and Beta?
- 5, 3
- 8, 15
- 3, 5
- 15, 8
Answer
8, 15
Reason — When performing a Cartesian product (cross join) of two tables, the resulting table retains all columns from both tables. Therefore, the degree of the Cartesian product is the sum of the degrees of the two tables i.e., Degree of Alpha + Degree of Beta = 5 + 3 = 8. Similarly, the cardinality of the Cartesian product is the total number of rows resulting from the cross join, which is the product of the cardinalities of the two tables, i.e., Cardinality of Alpha * Cardinality of Beta = 3 * 5 = 15.
Riya wants to transfer pictures from her mobile phone to her laptop. She uses Bluetooth Technology to connect two devices. Which type of network will be formed in this case?
- PAN
- LAN
- MAN
- WAN
Answer
PAN
Reason — A personal area network (PAN) is the interconnection of information technology devices within the range of an individual person, typically within 10 meters. Bluetooth technology is used to create PANs for short-range wireless communication between devices. In Riya's case, she is using Bluetooth to connect her mobile phone to her laptop within a range of about 10 meters, forming a PAN (Personal Area Network).
Which of the following will delete key-value pair for key = “Red” from a dictionary D1 ?
- delete D1("Red")
- del D1["Red"]
- del.D1["Red"]
- D1.del["Red"]
Answer
del D1["Red"]
Reason — The syntax to delete a key-value pair from a dictionary in Python is : del dictionary_name[key]
. Therefore, according to this syntax, del D1["Red"]
is correct statement."
Consider the statements given below and then choose the correct output from the given options:
pride = "#G20 Presidency"
print(pride[-2:2:-2])
- ndsr
- ceieP0
- ceieP
- yndsr
Answer
ceieP0
Reason — The code assigns the string "#G20 Presidency" to the variable pride
. The slicing operation pride[-2:2:-2]
starts from the second last character ("y"), which is at index -2, moves backward by 2 characters at a time due to the step value of -2, and stops before reaching the third character ("G"), which is at index 2. Hence, the output will be 'ceieP0'.
Which of the following statement(s) would give an error during execution of the following code ?
tup = (20, 30, 40, 50, 80, 79)
print(tup) #Statement 1
print(tup[3] + 50) #Statement 2
print(max(tup)) #Statement 3
tup[4] = 80 #Statement 4
- Statement 1
- Statement 2
- Statement 3
- Statement 4
Answer
Statement 4
Reason — The statement that would give an error during execution of the given code is Statement 4 (tup[4] = 80). This is because tuples in Python are immutable, meaning we cannot modify the elements of a tuple after it has been created. Here, it is attempting to assign 80 to the element at the index 4 of a tuple, which results in an error because tuples do not support item assignment.
What possible outputs(s) will be obtained when the following code is executed?
import random
myNumber = random.randint(0, 3)
COLOR = ["YELLOW", "WHITE", "BLACK", "RED"]
for I in range(1, myNumber):
print(COLOR[I], end = "*")
print()
- RED*
WHITE*
BLACK* - WHITE*
BLACK* - WHITE* WHITE*
BLACK* BLACK* - YELLOW*
WHITE*WHITE*
BLACK* BLACK* BLACK*
Answer
WHITE*
BLACK*
Reason — random.randint(0, 3)
will generate a random integer between 0 and 3. Possible outcomes are 0, 1, 2, or 3. Since 0 and 1 would make the loop invalid, we consider 2 and 3.
When myNumber
is 2:
The loop for i in range(1, myNumber)
will iterate over range(1, 2), which includes only the number 1. The code will print COLOR[1], which is "WHITE", followed by an asterisk (*). So, one of the possible outputs is:
WHITE*
When myNumber
is 3:
The loop for i in range(1, myNumber)
will iterate over range(1, 3), which includes the numbers 1 and 2. The code will print COLOR[1], which is "WHITE", followed by an asterisk (*), and then move to the next line. Then, it will print COLOR[2], which is "BLACK", followed by an asterisk (*). So, the other possible output is:
WHITE*
BLACK*
Since the output when myNumber
is 3 is among the possible outputs, it's the correct answer.
Fill in the blank:
The modem at the sender’s computer end acts as a ............... .
- Model
- Modulator
- Demodulator
- Convertor
Answer
Modulator
Reason — The modem at the sender's computer end acts as a modulator, which is responsible for converting digital data into analog signals for transmission over the communication channel.
Consider the code given below:
b = 100
def test(a):
............... #missing statement
b = b + a
print(a, b)
test(10)
print(b)
Which of the following statements should be given in the blank for #Missing Statement, if the output produced is 110?
- global a
- global b = 100
- global b
- global a = 100
Answer
global b
Reason — When we want to modify a global variable within a function in Python, we need to use the global
keyword followed by the name of the global variable. In this case, since the variable b is declared as a global variable outside the function, we need to declare it as a global variable again inside the function using global b
before attempting to modify its value.
State whether the following statement is True or False:
An exception may be raised even if the program is syntactically correct.
Answer
True
Reason — An exception can be raised even if the program is syntactically correct. This can happen due to various runtime errors such as division by zero, accessing an index out of range, trying to perform an operation on incompatible data types, etc. These types of errors are detected during the execution of the program and can lead to exceptions being raised, even if the program's syntax is correct.
Which of the following statements is FALSE about keys in a relational database?
- Any candidate key is eligible to become a primary key.
- A primary key uniquely identifies the tuples in a relation.
- A candidate key that is not a primary key is a foreign key.
- A foreign key is an attribute whose value is derived from the primary key of another relation.
Answer
A candidate key that is not a primary key is a foreign key.
Reason — A candidate key that is not chosen as the primary key remains a candidate key and is not automatically a foreign key.
Fill in the blank:
In case of ............... switching, before a communication starts, a dedicated path is identified between the sender and the receiver.
Answer
circuit
Which of the following functions changes the position of file pointer and returns its new position?
- flush()
- tell()
- seek()
- offset()
Answer
seek()
Reason — The seek() function in Python is utilised to relocate the file pointer within a file to a specific position. It also accepts an optional second argument, which denotes the starting point for determining this new position.
Assertion(A): List is an immutable data type.
Reasoning(R): When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable is created by the same name in memory.
- Both A and R are true, and R is the correct explanation of A.
- Both A and R are true, and R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Assertion is false but Reason is true.
Reason — List is a mutable data type. When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable with the updated value is created, and the variable name is reassigned to point to this new object in memory.
Assertion(A): Python Standard Library consists of various modules.
Reasoning(R): A function in a module is used to simplify the code and avoids repetition.
- Both A and R are true, and R is the correct explanation of A.
- Both A and R are true, and R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
Answer
Both Assertion and Reason are true but Reason is not the correct explanation for Assertion.
Reason — The Python Standard Library is a collection of modules and packages that provide a wide range of functionalities. A function in a module helps to organize code, simplify it, and avoid repetition which makes programming more efficient.
(i) Expand the following terms: POP3, URL
(ii) Give one difference between XML and HTML.
Answer
(i) POP3 – Post Office Protocol 3
URL – Uniform Resource Locator
(ii) One difference between XML and HTML:
HTML( Hyper text mark Up language) | XML (Extensible Markup Language) |
---|---|
It is a static web development language – only focuses on how data looks. It is used for only displaying data, cannot transport data. | It is a dynamic web development language – as it is used for transporting and storing data. |
(i) Define the term bandwidth with respect to networks.
(ii) How is http different from https ?
Answer
(i) Bandwidth is the maximum rate of data transfer over a given transmission medium or the amount of information that can be transmitted over a network.
(ii) HTTPS (Hyper Text Transfer Protocol Secure) is the protocol that uses SSL (Secure Socket Layer) to encrypt data being transmitted over the Internet. Therefore, HTTPS helps in secure browsing while HTTP does not.
The code given below accepts a number as an argument and returns the reverse number. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.
define revNumber(num):
rev = 0
rem = 0
While num > 0:
rem == num % 10
rev = rev * 10 + rem
num = num//10
return rev
print(revNumber(1234))
Answer
def revNumber(num): #correction 1
rev = 0
rem = 0
while num > 0: #correction 2
rem = num % 10 #correction 3
rev = rev * 10 + rem
num = num // 10
return rev #correction 4
print(revNumber(1234))
- correction 1 — The correct keyword to define a function is "def" not "define".
- correction 2 — Instead of "While" (capital W) in the while loop, it should be "while" (lowercase w).
- correction 3 — The comparison operator "==" in the line rem == num % 10 should be replaced with the assignment operator "=".
- correction 4 — Moved the "return" statement outside the while loop to return the reversed number after the loop completes.
Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an argument and displays the names (in uppercase) of the places whose names are longer than 5 characters. For example, Consider the following dictionary:
PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5:"Doha"}
The output should be:
LONDON
NEW YORK
Answer
PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5: "Doha"}
def countNow(PLACES):
for place in PLACES.values():
if len(place) > 5:
print(place.upper())
countNow(PLACES)
LONDON
NEW YORK
Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing length of each word of a string. For example, if the string is "Come let us have some fun", the tuple will have (4, 3, 2, 4, 4, 3).
Answer
def lenWords(STRING):
T = ()
L = STRING.split()
for word in L:
length = len(word)
T = T + (length, )
return T
Predict the output of the following code:
S = "LOST"
L = [10, 21, 33, 4]
D = {}
for I in range(len(S)):
if I % 2 == 0:
D[L.pop()] = S[I]
else:
D[L.pop()] = I + 3
for K, V in D.items():
print(K, V, sep = "*")
Answer
4*L
33*4
21*S
10*6
The code initializes variables S, L, and D, representing a string, list, and dictionary, respectively. The code iterates through the indices of string S. If the index is even, it assigns the popped element from list L as a key in dictionary D with the corresponding character from S as its value. If the index is odd, it assigns the popped element from L as a key in D with the value being the index plus 3. This process continues until the loop ends. After the loop, it prints each key-value pair from D, with keys and values separated by "*".
Write the Python statement for each of the following tasks using BUILT-IN functions/methods only:
(i) To insert an element 200 at the third position, in the list L1.
(ii) To check whether a string named, message ends with a full stop / period or not.
Answer
(i)
L1.insert(2, 200)
(ii)
message.endswith('.')
A list named studentAge stores age of students of a class. Write the Python command to import the required module and (using built-in function) to display the most common age value from the given list.
Answer
import statistics
print(statistics.mode(studentAge))
Ms. Shalini has just created a table named “Employee” containing columns Ename, Department and Salary. After creating the table, she realized that she has forgotten to add a primary key column in the table. Help her in writing an SQL command to add a primary key column EmpId of integer type to the table Employee. Thereafter, write the command to insert the following record in the table:
EmpId - 999
Ename - Shweta
Department: Production
Salary: 26900
Answer
SQL command to add primary key in the table:
ALTER TABLE Employee ADD EmpId INTEGER
PRIMARY KEY ;
SQL command for inserting data will be:
INSERT INTO Employee (EmpId, Ename, Department, Salary)
VALUES (999, "Shweta", "Production", 26900) ;
Zack is working in a database named SPORT, in which he has created a table named “Sports” containing columns SportId, SportName, no_of_players, and category. After creating the table, he realized that the attribute, category has to be deleted from the table and a new attribute TypeSport of data type string has to be added. This attribute TypeSport cannot be left blank. Help Zack write the commands to complete both the tasks.
Answer
SQL command to delete the attribute category from the table Sports:
ALTER TABLE Sports
DROP category ;
SQL command to add the attribute TypeSport to the table Sports:
ALTER TABLE Sports
ADD TypeSport char(10) NOT NULL ;
Predict the output of the following code:
def Changer(P, Q = 10):
P = P / Q
Q = P % Q
return P
A = 200
B = 20
A = Changer(A, B)
print(A, B, sep = '$')
B = Changer(B)
print(A, B, sep = '$', end = '###')
Answer
10.0$20
10.0$2.0###
The code snippet provided defines a function Changer
that takes two parameters P and Q, where Q is assigned a default value of 10. Inside the function, P is divided by Q and P is assigned the quotient, and then Q is assigned the remainder of P divided by Q. The modified P value is returned from the function. In the main code, variables A and B are initialized with values 200 and 20, respectively. The Changer function is called first with A and B as arguments, modifying the value of A. The updated values of A and B are then printed with a separator of '$'. Next, the Changer function is called again with only B as an argument, updating B. Finally, the updated values of A and B are printed again with a separator of '$' and an end marker of '###'.
Predict the output of the Python code given below:
Text1 = "IND-23"
Text2 = ""
I = 0
while I < len(Text1):
if Text1[I] >= "0" and Text1[I] <= "9":
Val = int(Text1[I])
Val = Val + 1
Text2 = Text2 + str(Val)
elif Text1[I] >= "A" and Text1[I] <= "Z":
Text2 = Text2 + (Text1[I + 1])
else:
Text2 = Text2 + "*"
I += 1
print(Text2)
Answer
ND-*34
The provided Python code initializes a variable Text1
with the string value "IND-23". Then it initializes an empty string variable Text2
and an index variable I
with the value 0. The while loop continues as long as I
is less than the length of Text1
. Within the loop, each character of Text1
is checked: if it's a digit (0-9), it increments the digit by 1 and appends it to Text2
; if it's an uppercase letter (A-Z), it appends the next character in Text1
to Text2
; otherwise, it appends an asterisk "*". After processing all characters, the final value of Text2
is printed.
Consider the table CLUB given below and write the output of the SQL queries that follow.
CID | CNAME | AGE | GENDER | SPORTS | PAY | DOAPP |
---|---|---|---|---|---|---|
5246 | AMRITA | 35 | FEMALE | CHESS | 900 | 2006-03-27 |
4687 | SHYAM | 37 | MALE | CRICKET | 1300 | 2004-04-15 |
1245 | MEENA | 23 | FEMALE | VOLLEYBALL | 1000 | 2007-06-18 |
1622 | AMRIT | 28 | MALE | KARATE | 1000 | 2007-09-05 |
1256 | AMINA | 36 | FEMALE | CHESS | 1100 | 2003-08-15 |
1720 | MANJU | 33 | FEMALE | KARATE | 1250 | 2004-04-10 |
2321 | VIRAT | 35 | MALE | CRICKET | 1050 | 2005-04-30 |
(i) SELECT COUNT(DISTINCT SPORTS) FROM CLUB;
(ii) SELECT CNAME, SPORTS FROM CLUB WHERE DOAPP<"2006-04-30" AND CNAME LIKE "%NA";
(iii) SELECT CNAME, AGE, PAY FROM CLUB WHERE GENDER = "MALE" AND PAY BETWEEN 1000 AND 1200;
Answer
(i)
+------------------------+
| COUNT(DISTINCT SPORTS) |
+------------------------+
| 4 |
+------------------------+
(ii)
+-------+--------+
| CNAME | SPORTS |
+-------+--------+
| AMINA | CHESS |
+-------+--------+
(iii)
+-------+-----+------+
| CNAME | AGE | PAY |
+-------+-----+------+
| AMRIT | 28 | 1000 |
| VIRAT | 35 | 1050 |
+-------+-----+------+
Write a function in Python to read a text file, Alpha.txt and displays those lines which begin with the word ‘You’.
Answer
The Alpha.txt file includes following data :
You To be or not to be, that is the question.
You The quick brown fox jumps over the lazy dog.
To infinity and beyond!
def test():
fobj1 = open("Alpha.txt", "r")
data = fobj1.readlines()
for line in data:
L = line.split()
if L[0] == "You":
print(line)
fobj1.close()
test()
You To be or not to be, that is the question.
You The quick brown fox jumps over the lazy dog.
Write a function, vowelCount() in Python that counts and displays the number of vowels in the text file named Poem.txt.
Answer
The Poem.txt file includes following data :
The sun sets in the west.
To be successful, one must work hard.
def vowelCount():
fobj = open("Poem.txt", "r")
data = str(fobj.read())
cnt = 0
for ch in data:
if ch in "aeiouAEIOU":
cnt = cnt + 1
print(cnt)
fobj.close()
vowelCount()
16
Consider the table Personal given below:
Table: Personal
P_ID | Name | Desig | Salary | Allowance |
---|---|---|---|---|
P01 | Rohit | Manager | 89000 | 4800 |
P02 | Kashish | Clerk | NULL | 1600 |
P03 | Mahesh | Superviser | 48000 | NULL |
P04 | Salil | Clerk | 31000 | 1900 |
P05 | Ravina | Superviser | NULL | 2100 |
Based on the given table, write SQL queries for the following:
(i) Increase the salary by 5% of personals whose allowance is known.
(ii) Display Name and Total Salary (sum of Salary and Allowance) of all personals. The column heading 'Total Salary' should also be displayed.
(iii) Delete the record of personals who have salary greater than 25000.
Answer
(i)
UPDATE Personal
SET Salary = Salary + Salary * 0.5
WHERE Allowance IS NOT NULL;
(ii)
SELECT Name, Salary + Allowance AS
"Total Salary" FROM Personal;
(iii)
DELETE FROM Personal
WHERE Salary > 25000;
A list, NList contains following record as list elements:
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined functions in Python to perform the specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object containing name of the city and country, which are not in India and distance is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the function should display “Stack Empty” when there are no elements in the stack.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734], ["Naypyidaw", "Myanmar", 3219], ["Dubai", "UAE", 2194], ["London", "England", 6693], ["Gangtok", "India", 1580], ["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'], ['Dubai', 'UAE'], ['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
Answer
(i)
NList=[["New York", "U.S.A.", 11734], ["Naypyidaw", "Myanmar", 3219], ["Dubai", "UAE", 2194], ["London", "England", 6693], ["Gangtok", "India", 1580], ["Columbo", "Sri Lanka", 3405]]
travel = []
def Push_element(NList):
for L in NList:
if L[1] != "India" and L[2] < 3500:
travel.append([L[0], L[1]])
return travel
print(Push_element(NList))
(ii)
travel = ['Naypyidaw', 'Myanmar'], ['Dubai', 'UAE'], ['Columbo', 'Sri Lanka']
def Pop_element():
while len(travel):
print(travel.pop())
else:
print("Stack Empty")
Pop_element()
Consider the tables PRODUCT and BRAND given below:
Table: PRODUCT
PCode | PName | UPrice | Rating | BID |
---|---|---|---|---|
P01 | Shampoo | 120 | 6 | M03 |
P02 | Toothpaste | 54 | 8 | M02 |
P03 | Soap | 25 | 7 | M03 |
P04 | Toothpaste | 65 | 4 | M04 |
P05 | Soap | 38 | 5 | M05 |
P06 | Shampoo | 245 | 6 | M05 |
Table: BRAND
BID | BName |
---|---|
M02 | Dant Kanti |
M03 | Medimix |
M04 | Pepsodent |
M05 | Dove |
Write SQL queries for the following:
(i) Display product name and brand name from the tables PRODUCT and BRAND.
(ii) Display the structure of the table PRODUCT.
(iii) Display the average rating of Medimix and Dove brands.
(iv) Display the name, price, and rating of products in descending order of rating.
Answer
(i)
SELECT PName, BName FROM PRODUCT P,
BRAND B WHERE P.BID = B.BID;
(ii)
DESC PRODUCT;
(iii)
SELECT BName, AVG(Rating) FROM PRODUCT
P, BRAND B
WHERE P.BID = B.BID
GROUP BY BName
HAVING BName = 'Medimix' OR
BName = 'Dove';
(iv)
SELECT PName, UPrice, Rating
FROM PRODUCT
ORDER BY Rating DESC;
Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has created a csv file named Result.csv, to store the results of students in different sports events. The structure of Result.csv is :
[St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'.
For efficiently maintaining data of the event, Vedansh wants to write the following user defined functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.
Answer
Python code to accept records from users :
def Accept():
sid = int(input("Enter Student ID"))
sname = input("Enter Student Name")
game = input("Enter name of game")
res = input("Enter Result")
headings = ["Student ID", "Student Name", "Game Name", "Result"]
data = [sid, sname, game, res]
f = open('Result.csv', 'a', newline = '')
csvwriter = csv.writer(f)
csvwriter.writerow(headings)
csvwriter.writerow(data)
f.close()
Python code to count the number of students who have won any event :
def wonCount():
f = open('Result.csv', 'r')
csvreader = csv.reader(f, delimiter = ',')
head = list(csvreader)
print(head[0])
for x in head:
if x[3] == "WON":
print(x)
f.close()
Meticulous EduServe is an educational organization. It is planning to setup its India campus at Chennai with its head office at Delhi. The Chennai campus has 4 main buildings – ADMIN, ENGINEERING, BUSINESS and MEDIA.
Block to Block distances (in Mtrs.)
From | To | Distance |
---|---|---|
ADMIN | ENGINEERING | 55 m |
ADMIN | BUSINESS | 90 m |
ADMIN | MEDIA | 50 m |
ENGINEERING | BUSINESS | 55 m |
ENGINEERING | MEDIA | 50 m |
BUSINESS | MEDIA | 45 m |
DELHI HEAD OFFICE | CHENNAI CAMPUS | 2175 km |
Number of computers in each of the blocks/Center is as follows:
block/center | Number of computers |
---|---|
ADMIN | 110 |
ENGINEERING | 75 |
BUSINESS | 40 |
MEDIA | 12 |
DELHI HEAD | 20 |
(a) Suggest and draw the cable layout to efficiently connect various blocks of buildings within the CHENNAI campus for connecting the digital devices.
(b) Which network device will be used to connect computers in each block to form a local area network?
(c) Which block, in Chennai Campus should be made the server? Justify your answer.
(d) Which fast and very effective wireless transmission medium should preferably be used to connect the head office at DELHI with the campus in CHENNAI?
(e) Is there a requirement of a repeater in the given cable layout? Why/ Why not?
Answer
(a) Below diagrams shows the cable layout for connecting CHENNAI campus blocks:
(b) Switch network device will be used to connect computers in each block to form a local area network.
(c) Admin block in chennai Campus should be made the server, as it has maximum number of computers.
(d) Using microwave wireless transmission medium is preferable for connecting the head office in Delhi with the campus in Chennai.
(e) No, a repeater is not required in the given cable layout as the length of transmission medium between any two blocks does not exceed 70m.
(i) Differentiate between r+ and w+ file modes in Python.
(ii) Consider a file, SPORT.DAT, containing records of the following structure: [SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the records with Sport name as “Basket Ball” to the file named BASKET.DAT. The function should return the total number of records copied to the file BASKET.DAT.
Answer
(i)
r+ mode | w+ mode |
---|---|
Primary function is reading. | Primary function is writing. |
If the file does not exist, it results in an error. | If the file does not exist, it creates a new file. |
(ii)
def copyData():
fobj = open("SPORT.DATA", "rb")
fobj1 = open("BASKET.DAT", "wb")
cnt = 0
try:
while True:
data = pickle.load(fobj)
print(data)
if data[0] == "Basket Ball":
pickle.dump(data, fobj1)
cnt +=1
except:
fobj.close()
fobj1.close()
return cnt
(i) How are text files different from binary files?
(ii) A Binary file, CINEMA.DAT has the following structure:
{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType(mtype), that accepts mtype as parameter and displays all the records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype.
Answer
(i)
Text files | Binary Files |
---|---|
Extension is .txt | Extension is .dat |
Data is stored in ASCII format that is human readable. | Data is stored in binary form (0s and 1s), that is not human readable. |
(ii)
def Searchtype(mtype):
fobj = open("CINEMA.DAT", "rb")
try:
while True:
data = pickle.load(fobj)
if data[2] == mtype:
print("Movie number:", data[0])
print("Movie Name:", data[1])
print("Movie Type:", data[2])
except EOFError:
fobj.close()
(i) Define the term Domain with respect to RDBMS. Give one example to support your answer.
(ii) Kabir wants to write a program in Python to insert the following record in the table named Student in MYSQL database, SCHOOL:
- rno(Roll number )- integer
- name(Name) - string
- DOB (Date of birth) – Date
- Fee – float
Note the following to establish connectivity between Python and MySQL:
- Username - root
- Password - tiger
- Host - localhost
The values of fields rno, name, DOB and fee has to be accepted from the user. Help Kabir to write the program in Python.
Answer
(i) Domain is a set of values from which an attribute can take value in each row.
For example, roll no field can have only integer values and so its domain is a set of integer values.
(ii)
import mysql.connector as mysql
con1 = mysql.connect(host = "localhost",
user = "root",
password = "tiger",
database = "SCHOOL")
mycursor = con1.cursor()
rno = int(input("Enter Roll Number:: "))
name = input("Enter the name:: ")
DOB = input("Enter date of birth:: ")
fee = float(input("Enter Fee:: "))
query = "INSERT into student values({}, '{}', '{}', {})".format(rno, name, DOB, fee)
mycursor.execute(query)
con1.commit()
print("Data added successfully")
con1.close()
(i) Give one difference between alternate key and candidate key.
(ii) Sartaj has created a table named Student in MYSQL database, SCHOOL:
- rno(Roll number )- integer
- name(Name) - string
- DOB (Date of birth) – Date
- Fee – float
Note the following to establish connectivity between Python and MySQL:
- Username - root
- Password - tiger
- Host - localhost
Sartaj, now wants to display the records of students whose fee is more than 5000. Help Sartaj to write the program in Python.
Answer
(i) One difference between alternate key and candidate key:
Alternate Key | Candidate Key |
---|---|
A candidate key is a set of attributes (columns) in a table that uniquely identifies each record or row. | An alternate key is a set of attributes (columns) in a table that uniquely identifies each record but is not designated as the primary key. |
(ii)
import mysql.connector as mysql
con1 = mysql.connect(host = "localhost",
user = "root",
password = "tiger",
database = "SCHOOL")
mycursor = con1.cursor()
query = "SELECT * FROM student WHERE fee > {}".format(5000)
mycursor.execute(query)
data = mycursor.fetchall()
for rec in data:
print(rec)
con1.close()