0% found this document useful (0 votes)
9 views32 pages

Computer Science With Python Class 12

The document contains a comprehensive answer key for a Class 12 Computer Science course focused on Python programming. It includes short and long answer questions covering various topics such as data types, functions, and control structures, along with example code snippets. Additionally, it highlights key differences between Python concepts and provides programming exercises for practical understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views32 pages

Computer Science With Python Class 12

The document contains a comprehensive answer key for a Class 12 Computer Science course focused on Python programming. It includes short and long answer questions covering various topics such as data types, functions, and control structures, along with example code snippets. Additionally, it highlights key differences between Python concepts and provides programming exercises for practical understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Computer Science with Python

CLASS - 12

Copyright @ Kips Learning Pvt. Ltd 2022.


Kips Computer Science with Python
Book XII
Answer Key

Ch-1 Revision Python 1

Section B: Unsolved Questions


A. Short answer type questions.
1. What is the output of the following Python expressions?
Ans.
a. False
b. True
c. True
d. False

2. What is the difference between input() and raw_input()?


Ans. The difference between raw_input() and input() is that the return type of raw_input() is always
string, while the return type of input need not be string only.

3. What is the difference between tuple and list data type?


Ans. The key difference between tuples and lists is that while the tuples are immutable objects the
lists are mutable. This means that tuples cannot be changed while the lists can be modified.

4. Out of the following, find those identifiers which cannot be used for naming variables
or functions in a Python program:
Ans. total*tax, 3rd Row, finally, Column 31

5. Suppose the passing mark for a subject is 35. Take the input of marks from the user and
check whether it is greater than passing marks or not.
Ans.
marks= float(input("Enter marks out of 100: "))
if(marks>=35):
print("Passing marks")
else:
print("Not passing marks")

6. Take two numbers and check whether the sum is greater than 5, less than 5 or equal to
5.
Ans.
a= float(input("Enter first number: "))
b= float(input("Enter second number: "))
c=a+b

Copyright @ Kips Learning Pvt. Ltd 2022.


if(c>5):
print("Sum is greater than 5")
elif(c<5):
print("Sum is less than 5")
else:
print("Sum is equal to 5")

7. Which string method is used to implement the following?


Ans.
a. len()
b. capitalize()
c. isalnum()
d. upper()
e. replace()

8. How many times will Python execute the code inside the following while loop? Justify
your answers.
Ans. This loop will not execute as the condition is false. In this program, the value of I is
initialised as i=0 and condition is i<0 and i>2. So, the control will not enter the loop at all.
Moreover, there is an indentation error.

9. Complete the given code to print the series 105, 98, 91, ….7.

for i in range(112, 0, -7):


print(i)

10. How many times is the following loop executed?


Ans. There is an indentation error.
Corrected code:

i=200
while(i<=300):
print(i)
i+=20

This loop will execute 6 times after removing syntax error.

11. Consider the following string:


Mysubject = "Computer Science"
What will be the output of the following string operations?
a. Cmue cec
b. Computer ScienceComputer Science Computer Science
c. cOMPUTER sCIENCE
d. urcn

Copyright @ Kips Learning Pvt. Ltd 2022.


B. Long answer type questions.
1. Write a program to input the monthly income of an employee and calculate the annual
income tax on the basis of the following:
Ans.
print("Tax On salary Calculation")
name= input("Enter name of employee:")
sal = float(input("Enter your monthly income:"))
asal=sal*12
print(name, " Your Annual salary is: ", asal)
if(asal>=600000): print("Annual taxable amount is: ", (asal-(asal*(8/100))))
elif(asal>=300000) and (asal<600000):
print("Annual taxable amount is: ", (asal-(asal*(6/100))))
elif(asal>=150000) and (asal<300000):
print("Annual taxable amount is: ", (asal-(asal*(2/100))))
elif(asal<150000):
print("Annual taxable amount is: ", (asal-(asal*(2/100))))

2. Write a program to accept a string and print it the following format:


Ans.
str1 = "Work"
l=len(str1)
x=0
for i in range(0,4):
print(str1[x:l], end=' ')
l=l-1
print()

3. Write a program to input any number and to print all the factors of that number.
Ans.
x = int(input("Enter any number"))
print("The factors of", x," are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
4. Write a program to input any number and to check whether the given number is
Armstrong or not.
Ans.
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num, "is an Armstrong number")
else:

Copyright @ Kips Learning Pvt. Ltd 2022.


print(num, "is not an Armstrong number")

5. Write a program to input two complex numbers and to find the sum of the given
complex numbers.
Ans.
first = complex(input('Enter first complex number: '))
second = complex(input('Enter first complex number: '))
addition = first + second
print('SUM = ', addition)

6. Write a program to print the following pyramid.


Ans.
rows = 6
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('')

7. Write a program to input username and password and to check whether the given
username and password are correct or not.
Ans.
dic = {'Py1' : "2021", 'Py2' : "2022", 'Py3' : "2023", 'Py6' : "1234", 'Py78' : "4321", 'Py100' : "1111",
'Py10' : "0000", 'Py21' : "2222", 'Py12' : "3333", 'Py9' : "4444" }
username = input("Enter username: ")
if username in dic:
password = input("Enter password: ")
if dic[username] == password:
print ("You are now logged into the system.")
else :
print ("Invalid password.")
else :
print ("You are not valid user.")

8. Write a program to input any string and to find the number of words in the string.
Ans.
test_string = "Chase your dreams"
print ("The original string is : " + test_string)
res = test_string.split()
print ("The list of words is : " + str(res))

Copyright @ Kips Learning Pvt. Ltd 2022.


Ch-2 Revision Python II
Section B: Unsolved Questions
A. Short answer type questions.
1. What are the characteristics of a tuple?
Ans. The characteristics of a Python tuple are:
• Tuples are ordered, indexed collections of data.
• Tuples can store duplicate values.
• Once data is assigned to a tuple, the values cannot be changed.
• Tuples allow you to store several data items in one variable.

2. How tuple is different from list data type?


Ans. The key difference between the tuples and lists is that while the tuples are immutable objects
the lists are mutable. This means that tuples cannot be changed while the lists can be modified.

3. What is the purpose of the sorted() function?


Ans. This function is used to sort the collection and returns the new collection, keeping the original
collection unchanged.

4. Explain the function max(), min(), and sum() in a tuple.


Ans. The max() function returns the maximum value from the tuple.
The min() function returns the minimum value from the tuple.
The sum() function returns the total value of all the items in a tuple.

5. What are the characteristics of a dictionary data type?


Ans. The following are the three main qualities of a dictionary:
1. Dictionaries are unordered: The key-value pairs in dictionary elements are not in any
order.
2. Dictionary keys are case-sensitive: In Python dictionaries, the same key name with
different case is handled as a separate key.
3. No duplicate keys are permitted.
4. Dictionary keys must be immutable: You can use strings, integers, or tuples as dictionary
keys, but you cannot use list data type for key.

6. How can you delete a Python list? Explain it with a suitable example.
Ans. There are three ways in which you can remove elements from List:
• Using the remove() method
myList = ["Shyam", 11, 22, 33, "Sejal", 22, 33, 11]
myList.remove(22)
myList

• Using the list object’s pop() method

myList = ["Shyam", 11, 22, 33, "Sejal", 22, 33, 11]


myList.pop(1)

• Using the del operator

Copyright @ Kips Learning Pvt. Ltd 2022.


myList = ["Shyam", 11, 22, 33, "Sejal", 22, 33, 11]
del myList[2]

7. Explain the purpose of the dict() function using an example.


Ans. The dict() function is used to create a dictionary with or without key-value pair passed
as an argument.
For example:
stud = dict()
print(stud)

8. Explain packing and unpacking process of tuple with the help of an example.
Ans. Unpacking a tuple means splitting the tuple’s elements into individual variables.
For example:
x,y=(2,4)

9. What will be the output:


Ans. [4, 3, 2]

10. Write the code to create the list of:


Ans.
a. veg=['potato', 'brinjal', 'pumpkin', 'peas', 'carrot']
b. vowels=['a','e','i','o','u']
c. num=[1,2,3,4,5,6,7,8,9,10]
d. sq=[1*1,2*2,3*3,4*4,5*5]
e. names=['Annu', 'Tanu', 'Manu', 'Radha', 'Sonu']

11. Explain the extend( ) function using suitable example.


Ans. The extend() function iterates over its arguments and adds each element to the list at
the end. The length of the list increases by the number of elements in the argument.
For example:
a = ['A']
b = ['Ball', 'Apple']
a.extend(b)
print(a)
['A', 'Ball', 'Apple']

12. Explain any one function of statistic and random module with a suitable example.
Ans.
mean(): This function can be used by importing statistic module in the program. It calculates
the arithmetic mean of the numbers in a sequence or set.
randint(): This function can be used by importing random module in the program. The
randint() function generates random integer values between the specific integer values. It
works only on integer values.

Copyright @ Kips Learning Pvt. Ltd 2022.


B. Long answer type questions.
1. Write a program to find the largest number from the following list. (without using
inbuilt function)
Ans.
x=[23, 12, 45, 67, 55]
print(max(x))

2. Write any one difference between the insert () and append() list functions.
Ans. Unlike append(), which can only add an element at the end of the list, the insert() function
allows us to add a specific element at a given index of the list.

3. Write a program to arrange the elements of following list in increasing order.


Ans.
A=[23, 12, 45, 32, 67, 33]
A.sort()
print(A)

4. Explain the following functions in reference to the lists with example:


Ans.
a. count(): The count() function returns the total number of elements with the specified value
provided in argument.
Example:
a=[1, 2, 3, 4, 1, 2, 3, 4, 3, 3, 3, 2, 5, 3]
x=a.count(3)
print(x)

b. clear(): This function removes all the items from the collection/list.
Example:
l= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l.clear()
print(l)

c. pop() : You can remove the item at the specified position and get its value with pop().
l = list(range(10))
print(l)
print(l.pop(0))

d. remove() : You can remove the first item from the list where its value is equal to the
specified value passed to the remove() function.

l = ['Cinthol', 'Dettol', 'Fiama', 'Dove', 'Pears']


print(l)
l.remove('Fiama')

5. Write a program to find the average value of the numbers in a given tuple of tuples.
Ans.
import statistics
tup = eval(input("Enter a tuple :-"))

Copyright @ Kips Learning Pvt. Ltd 2022.


sum = sum(tup)
print("Average =", sum / len( tup))
print("Mean =", statistics.mean( tup) )
6. Create a program for the Random Lottery Pick game.
Ans.
import random
lottery_tickets_list = []
print("Creating 100 random lottery tickets…")
# to get 100 ticket
for i in range(100):
lottery_tickets_list.append(random.randrange(1000000000, 9999999999))
winners = random.sample(lottery_tickets_list, 2)
print("Lucky 2 lottery tickets are", winners)

Ch-3 Functions
Section B: Unsolved Questions
A. Short answer type questions.
1. Is the return statement mandatory for every function?
Ans. Every function must have at least one return statement.

2. What are the default arguments? Explain with a suitable Python example.
Ans. Default values indicate that the function argument will take that value if no argument value is
passed during the function call.
Example:
def details(name, age=10):
print(name, age)
details(‘Arman’)

3. What is namespace in Python?


Ans. In Python, a namespace is a mechanism that gives each object a unique name. A variable or a
method can be considered an object. Python has its own namespace, which is kept in the form of a
Python dictionary.

4. Write a function that returns the greater of two numbers.


Ans.
def largest(x, y):
if x > y:
return x
else:
return y
x = int(input("Enter first number:"))
y = int(input("Enter second number:"))
result = largest(x, y)
print("Largest is:", result)

Copyright @ Kips Learning Pvt. Ltd 2022.


5. Write a function called ice_water that takes a number as input. Perform the following
operations:
Ans.
def icewater(x):
if x%3==0:
print("Ice")
elif x%5==0:
print("Water")
elif (x%3==0) and(x%5==0):
print("IceWater")
else:
print(x)
x = int(input("Enter number:"))
icewater(x)

6. Write a function for checking the speed of drivers. This function should have one
parameter: speed.
Ans.
def checkSpeed(speed):
if speed <= 70:
return "OK"
else:
speed1 = (speed-70)//5

if speed1 <= 12:


print(f"Point: {speed1}")

else:
print("License suspended")

checkSpeed(int(input("Enter speed: ")))

7. Write a function called mynumbers that takes a parameter called range. It should print
all the numbers between 0 and range with a label to identify the even and odd numbers.
Ans.
def evenodd(n):
for i in range(0, n+1):
if(i%2==0):
print(i, 'EVEN')
else:
print(i, 'ODD')
n=int(input("Enter range: "))
evenodd(n)

Copyright @ Kips Learning Pvt. Ltd 2022.


8. Write a function that returns the sum of multiples of 3 and 5 between 0 and limit
(parameter).
Ans.
def sumofm(r):
s=0
for i in range(1,r+1):
if ((i%3==0) or(i%5==0)):
s=s+i
print("sum of multiples of 3 and 5 is : ",s)

r=int(input("Enter range: "))


sumofm(r)

B. Long answer type questions.


1. What are the various parameters passing techniques?
Ans. There are three types of parameters/ arguments that Python supports:
a) Positional Arguments
b) Default Arguments
c) Keyword Arguments

2. What do you mean by the scope of the variable? Differentiate between the local scope
and globe scope with the help of an example.
Ans. A variable is only available inside a specific region of the program. This region of the
variable is called its scope. There are two types of scope in Python: Global and Local.
Global variables are those which are not defined inside any function and have a global scope
whereas local variables are those which are defined inside a function and its scope is limited to that
function only.

3. Describe user defined functions in Python with the help of an example.


Ans. A user-defined function enables you to define your own code to accomplish a
particular task.
Syntax:
def <function name>([ parameters ]):
< statement>
…..
Return
Example:
def mymsg():
global msg
msg = "How are you?"
mymsg()
print("Hello! " + msg)
4. Distinguish between keyword and default arguments.
Ans. Default values indicate that the function argument will take that value if no argument value is
passed during the function call.
Example:
def details(name, age=10):
print(name, age)

Copyright @ Kips Learning Pvt. Ltd 2022.


details(‘Arman’)
Output:
Arman 10
The keyword or named arguments in Python functions provide flexibility to provide values as
parameter in any order and sequence. That means, you can change the order of the arguments
while passing the values to the function in a function call, provided you mention the names of the
arguments. For example:
def area (l=5, b=10):
a=l*b
print(a)
area(b=5, l=3)
Output:
15
Thus, it is necessary to remember the sequence of parameters in case of default arguments, but
keyword arguments give you the flexibility to provide the values in any order using variable names.

5. Describe namespace and scoping in detail.


Ans. In Python, a namespace is a mechanism that gives each object a unique name. A variable or a
method can be considered an object. Python has its own namespace, which is kept in the form of a
Python dictionary.
A variable is only available inside a specific region of the program. This region of the variable is called
its scope. There are two types of scope in Python: Global and Local.

Global variables are those which are not defined inside any function and have a global scope
whereas local variables are those which are defined inside a function and its scope is limited to that
function only.

Ch-4 File Handling in Python


Section B: Unsolved Questions
A. Short answer type questions.
1. Write the appropriate access mode:
Ans.
a. Reading mode : r
b. Writing mode : w
c. Append mode : a

2. What is the difference between text file and binary file?


Ans. A text file is a sequence of ASCII or Unicode characters. It contains textual data and may be
saved in plain text or rich text formats.
A binary file is a data file that stores binary data. It may contain any type of formatted or
unformatted data encoded in binary format.

3. Explain the pickle module and its functions.


Ans. The pickle module is used to store objects and provide them later when needed.
Pickling/serialisation and unpickling/de-serialisation are two processes that a pickle module does.
Serialisation: it is the process of transforming data or an object in memory (RAM) to a stream of
bytes called byte streams.

Copyright @ Kips Learning Pvt. Ltd 2022.


De-serialisation: It is the inverse of the pickling process, where a byte stream is converted back to
Python objects.

4. How is seek() function different from tell() function?


Ans.
The seek() method moves the pointer in the file.
The tell() method in file handling returns the current location of the read/write pointer.

5. Explain the purpose of different access modes in binary files.


Ans. The access modes in binary files are as follows:
a. <rb> : it opens a file in read only mode.
b. <rb+> : it opens a file in read and write mode.
c. <wb> : it opens a file in write only mode.
d. <ab> : it opens a file in appending only mode.
e. <ab+> : it opens a file in read and append mode.

6. If a text file does not exist and you try to open it, then what will happen?
Ans. When you open a file for reading, if the file does not exist, the program will open an
empty file. When you open a file for writing, if the file does not exist, a new file is created.
When you open a file for writing, if the file exists, the existing file is overwritten with the
new content.

7. Explain the following:


Ans.
a. open(): The open() function is used to open a file in Python. This function returns a
file object, which is known as handle. File handle is used to read or change the file.

b. close(): The close() function in Python is used to close a file and release the resources
associated with it.

8. What is the purpose of the ‘with’ statement?


Ans. In Python, the ‘with’ statement is used to open a file and facilitates exception handling
to make the code clear and easy to comprehend.
Example:
with open(“names.txt”) as n:
data = file.read()

9. What is the advantage of CSV file format?


Ans. The advantages of CSV files are:
a. A simple, compact, and ubiquitous format for data storage.
b. A common format for data interchange.
c. It can be opened in popular spreadsheet packages like MS Excel, Calc, etc.
d. Nearly all spreadsheets and databases support import/export to CSV format.

10. Differentiate between the file mode r+ and rb+.


Ans. The r+ mode opens a file for both reading and writing. The file pointer is placed at the
beginning of the file. The rb+ mode opens a file for both reading and writing in binary format.

Copyright @ Kips Learning Pvt. Ltd 2022.


B. Long answer type questions.
1. Write a program to read the first 10 characters from the file(“data.txt”).
Ans
f = open('q1.txt', 'r')
print(f.read(10))
f.close()

2. Write a program to display the number of lines in a file.


Ans.
file_path = r"D:\Book-Work\Solutions\class 12\Python file-chapter 4\q1.txt"
lines_count = 0
with open(file_path, 'r') as f:
for l in f:
lines_count = lines_count +1
print("Total number of lines : ", lines_count)

3. Consider the following lines for the file "notes.txt" and predict the output of the Python
code given below:
Ans.
It has very simple
syntax an
d easy to code.

4. Write the output of the following, if the data stored in the file "quotes.txt" is given
below.
Ans.
A po
sitiv
e mindset brings positive things.

5. Write a function display_oddLines() to display odd number of lines from the text file.
Consider the above file-notes.txt for this question.
Ans.
def display_oddLines():
f = open("notes.txt")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
display_oddLines()

Copyright @ Kips Learning Pvt. Ltd 2022.


6. Write a function cust_data() to ask the users to enter their name and age to store data in
“customer.txt” file.

Ans.

def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("customer.txt","w")
f.write(data)
f.close()
cust_data()

7. Write a program to modify the record of a student in a file "data.csv".

Ans.
from csv import reader
from csv import writer
f1 = open("temp.csv","w")
d=csv.reader(f)
d1=csv.writer(f1)
next(f)
s=0
rollno = int(input("Enter roll number :"))
mn=input("Enter modified name :")
mm = int(input("Enter modified marks :"))
mr=[rollno,mn,mm]
header =["Rollno", "Name", "Marks"]
d1.writerow(header)
for i in d:
if int(i[0])==rollno:
d1.writerow(mr)
else:
d1.writerow(i)
os.remove("data.csv")
os.rename("temp.csv","data.csv")
f.close()
f1.close()

8. Mrs. Sugandha has stored the records of all the students of her class in a file named "class.dat".
The structure of the record is [Roll_number, Name, Percentage]. Write a function remedial( ) to
count the number of students who need remedial class. Consider that the students who have scored
less than 40 per cent will be there in the remedial class.
Ans.
import pickle
def remedial():
f = open("cls.dat","ab")
while True:
rn=int(input("Enter the rollno:"))

Copyright @ Kips Learning Pvt. Ltd 2022.


sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)
ch=input("Want more records? Yes:")
if ch.lower() not in 'yes':
break
f.close()
f1 = open("cls.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f1)
for s in data:
if s[2]<40:
cnt+=1
print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f1.close()
remedial()

Ch-5: Data structure


Section B: Unsolved Questions
A. Short answer type questions.
1. What is data structure in Python?
Ans. Data structures provide a method of arranging and storing data so that it can be accessed and
used effectively.

2. What are the different categories of data structures in Python? Give some examples.
Ans. Data structures are of two types:
Linear data structure: It stores data items in a sequential order.
Non-linear data structure: In non-linear data structure, data elements are not stored in a sequential
order.

3. Explain the term ‘top’ with respect to a stack.


Ans. Top is a pointer to the stack’s current location, which refers to the top most location of the
element.

4. Write and explain the various operations that can be performed on a stack.
Ans. Stack includes activities: push (adding) element, pop (deleting) elements, and accessing
elements from the TOP of the stack.

Copyright @ Kips Learning Pvt. Ltd 2022.


Push: The push operation means inserting an element into a stack. While inserting a new
element into an already full stack, the condition of overflow occurs.
Pop: The pop operation means removing a data element from the stack. While performing
pop operation on an empty stack, the condition of underflow occurs.

5. What are the applications of the stack data structure in real-life?


Ans. Following are the various applications of stack data structure:
• Evaluation of Arithmetic Expressions
• Backtracking
• Delimiter Checking
• Reversing a string
• Processing Function Calls
• Memory Management
• Floors in a building
• Clothes and books cabinet management

6. Fill in the blanks:


Ans.
a. Push
b. Pop
c. Traversing

7. Output:
Ans.
push: [1, 2, 3]
pop: [1, 2]
peek: 2
pop: [1]
peek: 1

B. Long answer type questions.


1. Explain the following conditions in terms of stack with a suitable Python example:
Ans
• Underflow Condition: When a stack is empty (i.e. TOP= -1) and we try to delete the element
from it, then this condition is called underflow condition.
• If the stack is full, and we try to add more elements to it, then it is said to be an overflow
condition. If stack is full, then push operation can’t be performed on it.
• Initially the stack is empty, and value of top is -1. When an element is inserted, the value of
top will be incremented by 1 and the element would be inserted at the array index specified
by the top variable. Thus, in an empty stack the pop operation cannot be performed.

Copyright @ Kips Learning Pvt. Ltd 2022.


2. Show the status of the stack after each operation and write the operation name.
Ans.

Empty k I t e t I S
stack t p P
I I I I I
k k k k k k K

a b c d e f g h I
Condition push push Push push pop pop push push
check

3. Write a Python program to implement the stack as a list and do the following.
Ans.
family=[ ]
family.push('Riya')
family.append('Riya')
family.append('Siya')
family.append("Manu")
print(family)

Ch-6: Computer Networks-1


Section B: Unsolved Questions
A. Short answer type questions.
1. What is a computer network?
Ans. It is an interconnection of autonomous computers to share data and resources through
transmission media.

2. What is internet?
Ans. The internet is a global network that connects millions of individuals all over the world. The
network of networks is called an internet.

3. What is a node?
Ans. An individual computer or device, which is connected to a network is called a node.

4. Define NSFNet.
Ans. The NSFNet network was solely designed for academic research. Many commercial
companies built their own networks, later connected via NSFNet and ARPANET, which
eventually became the internet.

5. Describe TCP/IP.
Ans. The TCP (Transmission Control Protocol) and IP (Internet Protocol) work together to ensure that
data transmission across the internet is consistent and reliable, regardless of the device or location.

Copyright @ Kips Learning Pvt. Ltd 2022.


6. What is data communication?
Ans. Data communication is the process of exchanging data between a sender and a
receiver via a transmission medium and protocols. It consists of five components: message,
sender, receiver, transmission medium, and protocols.

7. List the types of data communication.


Ans. There are three types of data communication:
• Simplex
• Half-duplex
• Full-duplex

8. What is data transfer rate? List different measurement units of data transfer rate.
Ans. The data transfer rate (DTR) is the amount of digital data that is moved from one place
to another at a certain period of time. The data transfer rate can be viewed as the speed of
travel of a given amount of data from one place to another.
Kbps (Kilobits per second), Mbps (Megabits per second), Gbps (Gigabits per second), and
Tbps (Terabits per second) are different data transfer rates.

9. Explain the following terms:


Ans.
a. Channel: It is a communication medium that allows data or information to be transmitted
from one node to another. Communication channels are often used to connect computers
over a network.
b. Baud: It is a measuring unit for data transfer rate. 1 baud is equal to 1 bit per second. It
represents only one signal change per second.

10. Write full forms of the following terms:


Ans.
a. NSFNet: National Science Foundation Network
b. TCP: Transmission Control Protocol
c. IP: Internet Protocol
d. STP: Shielded Twisted Pair
e. UTP: Unshielded Twisted Pair
f. Hz: Hertz
g. bps: bits per second

11. Name all the components of data communication.


Ans. There are five components involved in data communication:
Message: It is the information in any form of audio, text, picture etc which is to be communicated.
Sender: It refers to a device that sends information.
Receiver: it refers the device which receives the information.
Transmission medium: it refers to the physical path that carries information in the form of
signals/bits and travels from one place to another.
Protocols: A protocol is a set of rules that governs the data communication.

Copyright @ Kips Learning Pvt. Ltd 2022.


12. What is interspace?
Ans. The interspace is a global network that will facilitate knowledge manipulation through concept
navigation between community spaces.

13. What is transmission media? Distinguish between guided and unguided media.
Ans. Transmission media refers to the physical path that carries information in the form of
signals/bits and travels from one place to another. It can be divided into two categories:
Wired/Guided Media: It is a transmission medium that transmits the data using physical path from
one device to another.
Wireless/Unguided Media: It does not require the establishment of a physical link between two or
more devices interacting wirelessly.

14. What are the different types of twisted pair cables?


Ans. There are two types of twisted pair cables: shielded and unshielded
STP: It is enclosed within a foil or mesh shield.
UTP: UTP cable is a twisted pair cable with wires that are twisted together.

B. Long answer type questions.


1. Write a short note on ARPANET.
Ans. ARPANET stands for Advanced Research Projects Agency NET. ARPANET was the first network
that consisted of distributed control. It was first to implement TCP/IP protocols. It was the beginning
of the internet with use of these technologies.

2. Explain the working of the internet.


Ans. The internet is a telecommunication and data transfer system that lets a group of
autonomous computers to communicate across a range of media. It works based on a
packet routing network that follows the TCP/IP. TCP/IP ensures the transmission across the
internet is consistent and reliable, regardless of the device or location.

3. What are the different types of transmission media?


Ans. Transmission media refers to the physical path that carries information in the form of
signals/bits and travels from one place to another. It can be divided into two categories:
Wired/Guided Media: It is a transmission medium that transmits the data using physical path from
one device to another.
Wireless/Unguided Media: It does not require the establishment of a physical link between two or
more devices interacting wirelessly.

4. Describe the role of IP address.


Ans. A device on the internet or a local network is identified by its IP address, which must
be unique. The internet protocol is a set of rules that governs the format of data sent over
the internet or a local network. It is a method of determining a user’s unique identity.

5. What are the different types of switching techniques?


Ans. There are three types of switching techniques.
• Circuit switching: In this technique, a dedicated path is maintained between both
ends until the connection is terminated.
• Packet Switching: The routing of data in discrete quantities called packets, each with
a specified format and maximum size, is known as packet switching.

Copyright @ Kips Learning Pvt. Ltd 2022.


• Message Switching: It is also known as store and forward technique. A message is
received by an intermediary device in the switching office, which stores it until the
next device is ready to receive it.

6. Explain the different components of data communication.


Ans. There are five components involved in data communication:
Message: It is the information in any form of audio, text, picture, etc., which is to be communicated.
Sender: It refers to a device that sends information.
Receiver: It refers the device which receives the information.
Transmission medium: It refers to the physical path that carries information in the form of
signals/bits and travels from one place to another.
Protocols: A protocol is a set of rules that governs the data communication.

7. Explain the advantages of optical fiber cable over twisted pair cable.
Ans. Optical fiber is used for broadband communication, has a lower error rate during
transmission than traditional cable, and is far more durable than twisted pair and co-axial
cable.

8. Explain the purpose and advantages of coaxial cable.


Ans. Coaxial cable transmits data at a significantly faster rate than twisted pair cable. This it
can be utilised for broadband transmission. It can be used as a foundation for a shared cable
network.

9. What are the advantages of radio waves over infrared waves?


Ans. Radio waves have a longer wavelength than infrared light, in the electromagnetic
spectrum. Radio waves can reach the earth's surface, unlike most infrared light.
Radio waves enable accessibility, mobility and freedom from owner’s rights. Whereas
infrared waves, transmission is limited to a short distance.

10. Difference between guided and unguided transmission medium.


Ans. Transmission media refers to the physical path that carries information in the form of
signals/bits and travels from one place to another. It can be divided into two categories:
Wired/Guided Media: It is a transmission medium that transmits the data using physical path from
one device to another.
Wireless/Unguided Media: It does not require the establishment of a physical link between two or
more devices interacting wirelessly.

Copyright @ Kips Learning Pvt. Ltd 2022.


Ch-7: Computer Networks-II
Section B: Unsolved Questions
A. Short answer type questions.
1. What does TCP/IP stand for?
Ans. TCP/IP: Transmission Control Protocol / Internet Protocol

2. Write the full forms of the following terms:


Ans.
a. PPP : Point-to-Point Protocol
b. HTTPs : Hypertext Transfer Protocol
c. VoIP : Voice over Internet Protocol

3. Why is network device needed?


Ans. Network devices are hardware components that connect digital equipment like computers,
printers, and other electronic devices to the network.

4. What is the purpose of the repeater.


Ans. A repeater is an electronic device that amplifies an incoming signal and regenerates to
its original level to cover long distances.

5. What is the difference between a router and switch?


Ans. A switch is a computer networking device used to connect computers with other computers or
server computer.
Router has the capability to connect two or more different computer networks.

6. What is a Wi-Fi Card?


Ans. Wi-Fi cards are small. Easily portable cards that allow electronic devices to connect to
the internet over a wireless network.

7. What is the NIC (Network Interface Card)?


Ans. The Network Interface Card, also known as Ethernet card is an essential component of
every network and is used to link a computer to another computer or a server, using a cable.
The most basic function of an Ethernet card is to transport data from one network to
another.

8. What is the difference between wireless NIC and Ethernet NIC?


Ans. A “wireless network NIC” is a network interface card that communicates with the network
without a wired connection, usually using a Wi-Fi connection. An “ethernet NIC” is a network
interface card that communicates using wired Ethernet protocol. It is usually faster and more secure
than Wi-Fi.

9. What is WWW?
Ans. The World Wide Web, commonly known as the Web, is an information system where
documents and other web resources are identified by Uniform Resource Locators, which may be
interlinked by hyperlinks, and are accessible over the internet.

10. Explain web hosting and its types.

Copyright @ Kips Learning Pvt. Ltd 2022.


Ans. Web hosting is a service that provides websites with space on the internet. The types of web
hosting are as follows:
• Free Web Hosting
• Shared Web Hosting
• Dedicated Web Hosting
• Cloud Hosting

B. Long answer type questions.

Ans 1.
I. Suggested cable layout is shown in the
adjacent figure.
II. The most suitable place to house the server is
Training Compound as it has a maximum
number of computers.
III. (a) As per the suggested layout, he repeater
can be avoided as all distances are between
the compounds are <=100 m.
(b) Hub/Switch should be installed in the
Training Compound as it is hosting the server.
IV. (b) Optical Fiber.

Ans 2.

I. Since, the distance between Lib Wing and Admin Wing is small. So, type of networking is
small, i.e. LAN.
II. Since, maximum number of computers are in Student Wing, so suitable place to house the
server is Student Wing.
III. (a) Repeater should be installed between Student Wing and Admin Wing as distance is more
than 60 m.
(b) Switch should be installed in each wing to connect several computers.
IV. Broadband connection as it is economical with high speed.

Ans 3. Domain Name and URL


A URL (Uniform Resource Locator) is a full web address that is used to locate a specific online page.
While the domain is the website's name, a URL will take you to any of the website's pages. Every URL
includes a domain name as well as other information necessary to locate the desired page or piece
of content.

Ans 4.
a. Bus Topology: All the computers and network devices are connected by a single cable, called
the bus using interface connectors.
b. Star Topology: All the network devices and computers are separately connected to a central
device (hub, router, or switch).
c. Tree Topology: All the nodes are connected in a hierarchical manner. It is a typical network
topology that combines the benefits of both the bus and star topologies.

Copyright @ Kips Learning Pvt. Ltd 2022.


Ch-8: Database Concepts
Section B: Unsolved Questions
A. Short answer type questions.
1. What is the difference between primary key and foreign key?
Ans. A primary key uniquely identifies each record in a table. It cannot contain NULL values.
A foreign key is a field or set of fields that is used to establish a relation between two tables. Each
value in a column or columns in a foreign key must match the primary key of the referential table.
Foreign keys assist in the maintenance of data and referential integrity.

2. Describe the relational data model.


Ans. The relational data model is easy to understand and contains all the traits and capabilities
needed to process data efficiently. The data is organised into tables called relations, with each row
representing a record and the data or attributes are stored in table’s columns.

3. What is the difference between primary key and candidate key?


Ans. A primary key is a non-null key that uniquely identifies a record in a table. There can only be
one main primary key in a table. A candidate key is similar to a primary key and is used to identify a
record in a table. However, a table can have multiple candidate keys.

4. What is SQL Join?


Ans. In SQL, joins are used to connect two or more tables, with each other. The joins can be
used to fetch data from many tables as well as different data from the same table.

5. Define relational database.


Ans. The relational database is easy to understand and contains all the traits and capabilities needed
to process data efficiently. The data is organised into tables called relation, with each row
representing a record and the data or attributes are stored in the table’s columns.

6. What do you understand by cartesian product?


Ans. In a cartesian product (join), there is a join for each row of one table to every row of another
table. This usually happens when the matching column or ‘where’ condition is not specified.

7. Differentiate between ALTER and UPDATE statements.


Ans. The ALTER command is used to add, delete, and modify the attributes of the database's
relations (tables). The UPDATE command is used to update existing database records. By
default, the ALTER command sets all tuple values to NULL. The UPDATE command updates
the tuples with the values supplied in the command.

8. Write the use of DELETE and DROP commands.


Ans. DELETE is a Data Manipulation Language (DML) command and is used to remove tuples/records
from a relation/table. On the other hand DROP is a Data Definition Language (DDL) command and is
used to remove the named elements of schema like relations/table, constraints, or entire the
schema.

9. What is the purpose of the following clauses in a select statement?

Copyright @ Kips Learning Pvt. Ltd 2022.


Ans.
a. Order By: An ORDER BY clause in SQL specifies that an SQL SELECT statement returns a result
set with the rows being sorted by the values of one or more columns.
b. Group By: GROUP BY is used to apply aggregate functions to groups of rows defined by
having identical values in specified columns. If you don't use GROUP BY, either all or none of
the output columns in the SELECT clause must use aggregate functions.

10. Write an SQL query to create the EMP table.


Ans.
CREATE TABLE EMP
(EMPID integer NOT NULL PRIMARY KEY,
Deputed integer,
EmpName char(10),
Job char(10),
Manager integer,
HireDate date,
Salary integer,
Commission integer);

B. Long answer type questions.

1. Consider the relation ‘Hospital’ and write the SQL query for questions from (a) to (h).
Ans.
a. Select *
from Hospital
where Department = ‘Cardiology’;

b. Select Name
from Hospital
where Department = ‘Orthopedic’ and Sex=’F’;

c. Select Name, date_of_adm


from Hospital
order by date_of_adm;

d. Select name, charges, age


from Hospital
where sex=’M’;

e. Select count(*)
from hospital
where age>20;

f. Select Name
from Hospital
where Sex=’M’;

Copyright @ Kips Learning Pvt. Ltd 2022.


g. Delete from Hospital
where No=10;

h. Alter table Hospital


add Status char(25);

2. Consider the relation ‘Teacher’. Write the SQL queries for (a) to (f) and the output of
SQL commands for (g) to (h) given below:
Ans.

a. Select * from Teacher Where Department=’Computer’;


b. Select Name from Teacher Where Department=’History’ and Sex=’F’;
c. Select Name from Teacher order by Dateofjoining;
d. Select Name, Department, Salary from Teacher Where Sex=’F’;
e. Select count(*)
from Teacher
where Salary < 10000;
f. Insert into Teacher
values(8, ‘Mersa’, ‘Computer’, ‘1/1/2000’,12000, ‘M’);

g.

Min(Distinct Salary)

8000

h.

Sum(Salary)

17000

3. Write the queries of the following on the basis of the given table 'Faculty'.
Ans.
a.
Select *
from Faculty
where DOJ > (’31.12.1990’);

b.
Select *
from Faculty
where Fsal > 20000;

c.
Select Fname
from Faculty
where DOJ = (‘12.10.1980’);

Copyright @ Kips Learning Pvt. Ltd 2022.


d.
Select *
from Faculty
where Fname like 'A%';

e.
Select *
from Faculty
where Fsal > 25000 and Fname like '%N';

f.
Select count(*)
from Faculty
where Fsal > 40000 and Fname LIKE 'S%';

g.

Select *
from Faculty
order by Fname;

Ch-9: Interface of Python with SQL Database

Section B: Unsolved Questions


A. Short answer type questions.
1. Write a program that creates a database 'Doctor'. Then, create a table 'doc' in it.
Ans.
import mysql.connector
mydb=mysql.connector.connect(host ="localhost",user = "root ", password
="akshaj" )
mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE Doctor")


mycursor.execute("CREATE TABLE doc (docid integer, name varchar(255), dept
varchar(255), sal integer)")

2. Write a program to insert 5 records in the table where you can enter doctor’s id, name,
department, and salary.
Ans.
import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="root",password="akshaj",
database="Doctor")

mycursor = mydb.cursor()

sql = "INSERT INTO doc (docid, name, dept, sal) VALUES (%s, %s, %s, %s)"

Copyright @ Kips Learning Pvt. Ltd 2022.


val = [
(1,'Akshita', 'Cardiologist', 100000),
(2,'Anubhav', 'ENT', 50000),
(3,'Vishesh', 'Radiology', 500000),
(4,'Manya', 'Gynaecologist', 80000),
(5,'Tarsem', 'Cardiologist', 100000)
]

3. Write a program to increase the salary of a doctor by 2000, where the doctor belongs to the
Gynaecology department.
Ans.
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", password="akshaj",
database="Doctor")
mycursor = mydb.cursor()
sql = "UPDATE doctor SET sal = sal+2000 WHERE dept = 'Gynaecologist'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

4. Explain the purpose of the connect() function.


Ans.
The connect() function creates a connection between MySQL and Python. It is a function of
the mysql.connector package.

5. Write the purpose of execute() function.


Ans. The execute() method executes the given database operation (query or command). The
parameters found in the tuple or dictionary parameters are bound to the variables in the operation.
The execute() method runs the SQL query and return the result. Use cursor.fetchall() or fetchone() or
fetchmany() to read query result.

6. Explain the update method by giving the suitable example.


Ans. Existing records can be updated in table by using UPDATE statement and then commit the
transaction.
Example:

import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", password="akshaj",
database="Doctor")
mycursor = mydb.cursor()
sql = "UPDATE doctor SET sal = 100000 WHERE dept = 'Gynaecologist'"
mycursor.execute(sql)
mydb.commit()

7. Write a program to update the department to ENT specialist, where doctor’s name is
'Durga'.
Ans.
import mysql.connector

Copyright @ Kips Learning Pvt. Ltd 2022.


mydb =
mysql.connector.connect(host="localhost",user="root",password="akshaj",database="Doct
or")
mycursor = mydb.cursor()
sql = "UPDATE doctor SET dept = ‘ENT’ WHERE name = “Durga'"
mycursor.execute(sql)
mydb.commit()

8. What is the purpose of commit statement?


Ans. The commit() function sends a commit command to the MySQL server, committing the current
transactions.

9. Write the steps to connect MySQL server with Python.


Ans. The steps to establish a connection with MySQL:
• Start Python.
• Import the packages required to connect to the MySQL server.
• Open a connection to a new database.
• Create a cursor instance and execute an SQL query.
• Extract data from the result set.
• Close the connection to the MySQL Server.

10. Delete the record from the doctor table, where salary is greater than 50000.
Ans.
import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="root",password="akshaj",
database="Doctor")

mycursor = mydb.cursor()

sql = "DELETE FROM doctor WHERE sal> 50000;

mycursor.execute(sql)

mydb.commit()

B. Long answer type questions.


1. Using Python-DB (MySQL), perform the following operations:
Ans.
a.
import mysql.connector

mydb=mysql.connector.connect( host ="localhost",user = "root ", password


="akshaj" )

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE Employee")

Copyright @ Kips Learning Pvt. Ltd 2022.


b.
mycursor.execute("CREATE TABLE emp ( id integer, name varchar(255), dept
varchar(255), sal integer)")

c.

import mysql.connector

mydb = mysql.connector.connect(host="localhost",user="root",password="akshaj",
database="Employee")

mycursor = mydb.cursor()

sql = "INSERT INTO emp (docid, name, dept, sal) VALUES (%s, %s, %s, %s)"
val = [
(1,'Akshita', 'sales', 10000),
(2,'Anubhav', 'sales', 5000),
(3,'Vishesh', 'production', 5000),
(4,'Manya', ' marketing', 8000),
(5,'Tarsem', 'quality', 1000)
]

d.

import mysql.connector

mydb =
mysql.connector.connect(host="localhost",user="root",password="akshaj",
database="Employee")

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM emp")

myresult = mycursor.fetchall()

for x in myresult:
print(x)

e.
import mysql.connector

mydb =
mysql.connector.connect(host="localhost",user="root",password="akshaj",
database="Employee")

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM emp Where name = "Ajay Mehta")

myresult = mycursor.fetchone()

Copyright @ Kips Learning Pvt. Ltd 2022.


print(myresult)

2. Using Python-DB (MySQL) perform the following operations:


Ans.
a.
import mysql.connector

mydb=mysql.connector.connect( host ="localhost",user = "root ", password


="akshaj" )

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE School")

b.
mycursor.execute("CREATE TABLE teacher ( id integer, name varchar(255),
dept varchar(255), sal integer)")

c.
import mysql.connector

mydb = mysql.connector.connect(host="localhost",user="root",password="akshaj",
database="School")

mycursor = mydb.cursor()

sql = "INSERT INTO teacher (teachid, name, sub, sal) VALUES (%s, %s, %s, %s)"
val = [
(1,'Akshita', 'eng', 10000),
(2,'Anubhav', 'CS', 5000),
(3,'Vishesh', 'Math', 5000),
(4,'Manya', ' Eng', 8000),
(5,'Tarsem', 'Eng', 1000)
]

d.
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", password="akshaj",
database="School")
mycursor = mydb.cursor()
sql = "UPDATE Teacher SET sub = ‘Physics’ WHERE name = "Priyanka"
mycursor.execute(sql)
mydb.commit()

e.
import mysql.connector

mydb = mysql.connector.connect(host="localhost", user="root", password="akshaj",


database="School")

Copyright @ Kips Learning Pvt. Ltd 2022.


mycursor = mydb.cursor()

sql = "DELETE FROM teacher WHERE id= 5”

mycursor.execute(sql)

mydb.commit()

3. Explain all the methods available for select query in MySQL. Give a suitable Python-DB example
for each function.

Ans. The select query in MySQL can be used to retrieve data from a table. There are two functions
used to fetch the result set.

a) Fetchone(): the fetchone() method is used to retrieve only one row from the result set.
b) Fetchall(): The fetchall() method is used to get the entire result of a query.

Copyright @ Kips Learning Pvt. Ltd 2022.

You might also like