0% found this document useful (0 votes)
27 views54 pages

XII CS ALL Chapters Questions

The document contains a series of questions and answers related to Python functions and exception handling, including multiple choice, assertion reason, and short answer questions. It covers topics such as user-defined functions, parameters, variable scope, and exception handling constructs like try-except blocks. Additionally, it provides code snippets and explanations for various programming concepts in Python.

Uploaded by

Samiran Biswas
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)
27 views54 pages

XII CS ALL Chapters Questions

The document contains a series of questions and answers related to Python functions and exception handling, including multiple choice, assertion reason, and short answer questions. It covers topics such as user-defined functions, parameters, variable scope, and exception handling constructs like try-except blocks. Additionally, it provides code snippets and explanations for various programming concepts in Python.

Uploaded by

Samiran Biswas
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/ 54

Unit-1: Functions (Questions)

Multiple Choice Questions


1. Which type of function is the `print()` function in Python?
A. Built-in function B. User-defined function C. Module function D. None of the above
2. When you create your own functions, they are called?
A) built-in functions B) user-defined functions C) control functions D) None of the above
3. What is the primary purpose of user-defined functions in Python?
A. Enhance code readability B. Reduce code complexity
C. Promote code reusability D. All of the above
4. Which keyword is used to define a function in Python?
A. define B. function C. def D. define_function
5. Which of the following items are present in the function header?
(a) Function name only (b) Parameter list only
(c) Both function name and parameter list (d) return value
6. What is the role of parameters in a function?
A. They store the function's return value.
B. They hold data that can be accessed from outside the function.
C. They act as placeholders for input values.
D. They determine the function's name.
7. Which one of the following is the correct way of calling a function?
A) function_name() B) call function_name()
C) ret function_name() D) function function_name()
8. Pick one of the following statements to correctly complete the function body in the given code snippet.
def f(number):
# Missing function body
print (f(5))
(a) return “number” (b) print(number) (c) print(“number”) (d) return number
9. In Python, what happens when a function is called?
A. Control moves to the next line in the function.
B. Control moves to the function's definition.
C. Control is transferred to the function and executes its code.
D. Control is transferred to the main program
10. What keyword is used to return a value from a function?
A. return B. value C. result D. yield
11. What is the default return value for a function that does not return any value explicitly?
(a) None (b) int (c) double (d) null
12. When using positional parameters in a function, how are arguments matched to parameters?
A. Based on alphabetical order B. Based on their names
C. Based on their positions D. Randomly
13. Which of the following is an example of a default parameter in a function?
A. def greet(name="Guest") B. def greet(name)
C. def greet(name, default="Guest") D. def greet()
14. Which of the following statements is not true for parameter passing to functions?
(a) You can pass positional arguments in any order.
(b) You can pass keyword arguments in any order.
(c) You can call a function with positional and keyword arguments.
(d) Positional arguments must be before keyword arguments in a function call
15. Which of the following function header is correct?
(a) def f(a=1,b): (b) def f(a=1,b,c=2):
(c) def f(a=1, b=1, c=2): (d) def f(a=1,b=1,c=2,d);
16. What is the scope of a variable defined outside of any function?
A. Global scope B. Local scope C. Module scope D. Function scope
17. Variables defined inside a function have which scope?
A. Global scope B. Local scope C. Module scope D. Function scope
18. Identify the incorrect statement?
A) The variables used inside function are called local variables.
B) The local variables of a particular function can be used inside other functions, but these cannot be
used in global space
C) The variables used outside function are called global variables
D) In order to change the value of global variable inside function, keyword global is used.
19. What is the order of resolving scope of a name in a python program? (L: Local namespace, E: Enclosing
namespace, B: Built-In namespace, G: Global namespace)
(a) BGEL (b) LEGB (c) GEBL (d) LBEG
20. The .........................refers to the order in which statements are executed during a program run.
(a) Token (b) Flow of execution (c) Iteration (d) All of the above
Assertion Reason Questions
A. Both assertion and reason are true, and the reason is the correct explanation of the assertion.
B. Both assertion and reason are true, but the reason is not the correct explanation of the assertion.
C. Assertion is true, but the reason is false.
D. Assertion is false, but the reason is true.
1. Assertion: User-defined functions enhance code reusability.
Reason: They allow you to define your own keywords in Python (A)
2. Assertion: The primary purpose of default parameters is to restrict the values that can be passed to a
function.
Reason: Default parameters allow you to specify a value that is used when an argument is not provided.
(B)
3. Assertion (A):- If the arguments in a function call statement match the number and order of arguments
as defined in the function definition, such arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains default argument(s) followed by
positional argument(s). (C)
4. Assertion: Default parameters in Python functions are mandatory.
Reason: Default parameters are automatically provided when you call a function. (B)
5. Assertion: Local Variables are accessible only within a function or block in which it is declared.
Reason: Global variables are accessible in the whole program. (B)
Short Answer Questions
1. Explain the role of parameters in a Python function.
Answer: Parameters are placeholders in a function's definition used to receive input data. They allow
functions to work with different values each time they are called.
2. Provide an example of a user-defined function with default parameters and explain its use.
Answer: `def greet(name="Guest"):` is an example. It greets a person by name, defaulting to "Guest" if
no name is provided
3. How does Python match arguments to positional parameters in a function?
Answer: Python matches arguments to positional parameters based on their order of appearance. The
first argument corresponds to the first parameter, the second to the second, and so on.
4. Explain the concept of variable scope in Python, specifically the difference between global and local
scope.
Answer: Variable scope refers to where a variable can be accessed. In Python, variables defined outside
any function have global scope and can be accessed from anywhere. Variables defined inside a function
have local scope and can only be accessed within that function.
5. Write a Python function to calculate the factorial of a number and explain how it works.
def factorial(n) :
f=1
for n in range(1,n+1):
f*=n
return f
factorial(6)
This function calculates the factorial of a number `n` by repeatedly multiplying `n` with the previous
iteration value of n in the loop.
6. Explain the difference between keyword arguments and positional arguments in Python functions.
Answer: Keyword arguments are passed with the parameter name, like
`function_name(param_name=value)`, allowing you to specify which argument corresponds to which
parameter. Positional arguments are passed based on their order.
7. What will be the output of the following code?
def my_func():
x = 10
while x > 0:
print(x)
x=x-2
my_func()
a) 10 8 6 4 2 b) 10 9 8 7 6 5 4 3 2 1 c) 10 7 4 1 d) 10 5
8. What will be the output of the following code?
a = 5 def
foo():
global a
a += 1
foo()
print(a)
a) 5 b) 6 c) 10 d) NameError: name 'a' is not defined
9. What will be the output of the following code?
def compute_average(numbers):
total = 0
count = 0
for num in numbers:
total += num
count += 1
return total / count
marks = [80, 90, 75, 95, 85]
average = compute_average(marks)
print("Average:", average)
a) Average: 85 b) Average: 85.5 c) Average: 85.0 d) Average: 80, 90, 75, 95, 85
10. What will be the output of the following code?
def func(x, y=2, z=3):
return x + y + z
result = func(1, z=4)
print(result)
a) 6 b) 8 c) 7 d) 11
11. What is the output of the following code snippet?
def foo(x=0):
x += 1
return x
result = foo(5) + foo(3)
print(result)
a) 10 b) 9 c) 8 d) 7
12. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with
each correction underlined.
def execmain(): Answer:
x = input("Enter a number:") def execmain():
if (abs(x)= x): x = int(input("Enter a number:"))
print("You entered a positive number") if (abs(x)== x):
else: print("You entered a positive number")
x=*-1 else:
print("Number made positive : ",x) x*=-1
execmain() print("Number made positive : ",x)
execmain()
13. Anita has written a code to input a number and check whether it is prime or not. His code is having
errors. Rewrite the correct code and underline the corrections made.
def prime(): Answer:
n=int(input("Enter number to check :: ") def prime():
for i in range (2, n//2): n=int(input("Enter number to check :: "))
if n%i=0: for i in range (2, n//2):
print("Number is not prime \n") if n%i==0:
break print("Number is not prime \n")
else: break
print("Number is prime \n’) else:
print("Number is prime \n”)
14. What is the output of the program given below?
x = 75
def func (x) :
x = 10
func (x)
print ('x is now', x)
Answer: x is now 75
15. Divyansh, a python programmer, is working on a project which requires him to define a function with
name CalculateInterest(). He defines it as:
def CalculateInterest(Principal,Rate=.06, Time): # Code
But this code is not working, Can you help Divyansh to identify the error in the above function and with
the solution?
Answer: Yes, here non-default argument is followed by default argument which is wrong as per python’s
syntax. (while passing default arguments to a function ,all the arguments to its right must also have
default values, otherwise it will result in an error.)
16. Write a function that takes a positive integer and returns the one’s position digit of the integer.
Answer:
def getOnes(num):
oneDigit=num%10 # return the ones digit of the integer num
return oneDigit
getOnes(234)
17. Write a user defined function to print the odd numbers from a given list passed as an argument.
Sample list: [1,2,3,4,5,6,,7,8,9,10]
Expected Result: [1,3,5,7,9]
Answer:
def odd_num(list):
odd=[]
for n in list:
if n%2!=0:
odd.append(n)
return odd
print(odd_num([1,2,3,4,5,6,7,8,9,10]))
18. Which line in the given code(s) will not work and why?
def interest(p,r,t=7): Answer:
I=(p*r*t) Line 2: positional argument must not be followed
print(interest(20000,.08,15)) #line 1 by keyword argument, i.e., positional argument
print(interest(t=10, 20000, 0.75)) #line 2 must appear before a keyword argument.
print(interest(50000, 0.7)) #line 3 Line 4: There is no keyword argument with name
print(interest(p=10000,r=.06,time=8)) #line 4 ‘time’
print(interest(80000, t=10)) #line 5 Line 5: Missing value for positional arguments, R.

19. Write a Python Program to Make a Simple Calculator using functions.


def add(P, Q): # This function is used for adding two numbers
return P + Q
def subtract(P, Q): # This function is used for subtracting two numbers
return P - Q
def multiply(P, Q): # This function is used for multiplying two numbers
return P * Q
def divide(P, Q): # This function is used for dividing two numbers
return P / Q
# Now we will take inputs from the user
print ("Please select the operation.")
print ("a. Add")
print ("b. Subtract")
print ("c. Multiply")
print ("d. Divide")
choice = input("Please enter choice (a/ b/ c/ d): ")
num_1 = int (input ("Please enter the first number: "))
num_2 = int (input ("Please enter the second number: "))
if choice == 'a':
print (num_1, " + ", num_2, " = ", add(num_1, num_2))
elif choice == 'b':
print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))
elif choice == 'c':
print (num1, " * ", num2, " = ", multiply(num1, num2))
elif choice == 'd':
print (num_1, " / ", num_2, " = ", divide(num_1, num_2))
else:
print ("This is an invalid input")
Unit-1: Exception Handling (Questions)
Multiple Choice Questions
1. Which of the following is the primary purpose of exception handling in programming?
A. To intentionally crash the program
B. To ignore errors and continue program execution
C. To gracefully manage and recover from unexpected errors
D. To create errors for testing purposes
2. What is the primary role of the `try` block in a try-except construct?
A. To execute code that may raise an exception
B. To handle exceptions
C. To indicate the end of the try-except construct
D. To prevent exceptions from occurring
3. In a try-except block, if an exception occurs, which block is executed?
A. The try block B. The except block
C. Both try and except blocks simultaneous D. None of the above
4. What is the purpose of the `finally` block in exception handling?
A. To specify the types of exceptions to catch
B. To execute code regardless of whether an exception occurred or not
C. To create custom exceptions
D. To prevent exceptions from propagating
5. Which keyword is used to specify the type of exception to catch in an except block?
A. `catch` B. `try` C. `except` D. `handle`
6. Which exception is raised when attempting to access a non-existent file?
A. FileNotFoundError B. FileNotAccessibleError
C. NonExistentFileError D. InvalidFileAccessError
7. What type of error does a `ValueError` exception typically represent in Python?
A. A network-related error B. A division by zero error
C. An error related to invalid data conversion. D. A file handling error
8. What is the main purpose of using a `try-except-finally` construct?
A. To create custom exceptions
B. To ensure that no exceptions are raised
C. To gracefully manage exceptions and execute cleanup code
D. To replace if-else statements
9. What happens if an exception is raised in the `finally` block?
A. The program crashes
B. The exception is caught and handled by the `except` block
C. The program continues executing normally
D. The `finally` block cannot raise exceptions
10. What will be the output of the following code?
try:
print(10 / 0)
except ZeroDivisionError as e:
print("Error:", str(e))
finally:
print("Finally block")
a) Error: Division by zero Finally block b) Error: Index out of range Finally block
c) Error: None Finally block d) The code will raise an exception and terminate.

11. What will be the output of the following code?


try:
print("Hello" + 123)
except TypeError:
print("Error: Type mismatch")
else:
print("No error")
a) Hello123 No error b) Error: Type mismatch No error
c) Error: Type mismatch d) The code will raise an exception and terminate.
Assertion Reason Questions
A. Both assertion and reason are true, and the reason is the correct explanation of the assertion.
B. Both assertion and reason are true, but the reason is not the correct explanation of the assertion.
C. Assertion is true, but the reason is false.
D. Assertion is false, but the reason is true.
1. Assertion: The `try` block is optional in a try-except construct.
Reason: You cannot have an `except` block without a corresponding `try` block. Answer: D
2. Assertion: The `finally` block is executed only if an exception occurs in the `try` block.
Reason: The `except` block is used exclusively for handling exceptions. Answer: D

Short Answer Questions


1. Differentiate between a `try-except` block and a `try-except-finally` block.
Answer: A `try-except` block handles exceptions by catching and handling specific errors but does not
guarantee that certain cleanup operations will be performed. A `try-exceptfinally` block, on the other
hand, ensures that the code within the `finally` block executes, making it suitable for cleanup operations.
2. Write a Python code snippet that demonstrates the use of a `try-except` block to handle the following
scenario: Attempting to open a file named "data.txt" and handling the `FileNotFoundError` by printing
an error message.
Answer:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("Error: File not found.")
3. Can you provide an example of using the `finally` block to ensure proper resource cleanup? Explain
why it is important.
Answer:
try:
file = open("sample.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close() # Ensures that the file is always closed, even if an exception occurs. It is
important to close the file properly to release resources and avoid potential issues, such as data
corruption.
Unit-1: File Handling – Text Files (Questions)
Multiple Choice Questions
1. Which of the following functions is used to open a file in Python for reading?
a) read() b) open() c) write() d) close()
2. What is the correct syntax to open a file named "data.txt" in write mode in Python?
a) file = open("data.txt", "r") b) file = open("data.txt", "w")
c) file = open("data.txt", "a") d) file = open("data.txt", "x")
3. Which method is used to read a single line from a file object in Python?
a) readlines() b) readline() c) read() d) write()
4. Which of the following modes in file handling allows both reading and writing to a file in Python?
a) "r" b) "w" c) "a" d) "r+"
5. Which method is used to write a string to a file in Python?
a) write() b) read() c) append() d) delete()
6. What is the correct way to close a file object after reading or writing in Python?
a) file.close() b) close(file) c) file.exit() d) exit(file)
7. What is the purpose of the seek() method in file handling?
a) To close the file after reading or writing b) To move the file pointer to a specific position in the file
c) To check if the file is readable or writable d) To delete the contents of the file
8. Which method is used to check the current position of the file pointer in Python?
a) current() b) position() c) tell() d) pointer()
9. How can you read the contents of a file line by line in Python?
a) Use the readlines() method b) Use the read() method
c) Use the write() method d) Use the close() method
10. Which method is used to read the entire contents of a file as a single string?
a) read() b) readline() c) readlines() d) write()
11. How can you ensure that a file is automatically closed after its operations are completed?
a) Using the close() method b) Using the flush() method
c) Using the with statement d) None of the above
12. How do you check if a file exists before opening it in Python?
a) Use the exists() function from the os module b) Use the open() function with the try-except block
c) Use the isfile() function from the os.path module d) All of the above
13. Which mode should be used when opening a file for reading only?
a) 'r' b) 'w' c) 'a' d) 'x'
14. Which of the following statements is true regarding file objects in Python?
a) File objects can be directly printed to display their contents.
b) File objects can only be used for reading files, not writing.
c) File objects have a 'write' method but not a 'read' method.
d) File objects must be explicitly closed using the 'close' method.
15. Consider the following code snippet:
file = open("data.txt", "r")
content = file.read()
file.close()
print(content)
What does this code do?
A) Opens the "data.txt" file in read mode, reads its contents, closes the file, and prints the content.
B) Opens the "data.txt" file in write mode, reads its contents, closes the file, and prints the content.
C) Opens the "data.txt" file in read mode, writes new content, closes the file, and prints the content.
D) Opens the "data.txt" file in read mode, appends new content, closes the file, and prints the content.
16. Consider the following code snippet:
file = open("data.txt", "w")
file.write("Hello, World!")
file.close()
What does this code do?
A) Opens the "data.txt" file in read mode, reads its contents, and writes "Hello, World!" to the file.
B) Opens the "data.txt" file in write mode, writes "Hello, World!" to the file, and closes the file.
C) Opens the "data.txt" file in write mode, reads its contents, and writes "Hello, World!" to the file.
D) Opens the "data.txt" file in append mode, appends "Hello, World!" to the file, and closes the file.
17. Consider the following code snippet:
file = open("data.txt", "a")
file.write("Hello, World!")
file.close()
What does this code do?
A) Opens the "data.txt" file in read mode, reads its contents, and appends "Hello, World!" to the file.
B) Opens the "data.txt" file in write mode, writes "Hello, World!" to the file, and closes the file.
C) Opens the "data.txt" file in append mode, appends "Hello, World!" to the file, and closes the file.
D) Opens the "data.txt" file in append mode, reads its contents, and appends "Hello, World!" to the file
18. Consider the following code snippet:
file = open("data.txt", "r")
lines = file.readlines()
file.close()
print(len(lines))
What does this code do?
A) Opens the "data.txt" file in write mode, reads the number of lines in the file, closes the file, and prints
the count.
B) Opens the "data.txt" file in read mode, reads the number of lines in the file, closes the file, and
prints the count.
C) Opens the "data.txt" file in append mode, reads the number of lines in the file, closes the file, and
prints the count.
D) Opens the "data.txt" file in read mode, writes the number of lines in the file, closes the file, and prints
the count.
Assertion Reason Questions
A. Both assertion and reason are true, and the reason is the correct explanation of the assertion.
B. Both assertion and reason are true, but the reason is not the correct explanation of the assertion.
C. Assertion is true, but the reason is false.
D. Assertion is false, but the reason is true.
1. Assertion(A): an open file can be close using close() function.
Reason(R): sometimes the data written onto files is held in memory until the file is closed.
Ans: i. Both A and R are true and R is the correct explanation for A
2. Assertion(A): ab+ mode is used for both appending and reading binary files and move file pointer at end.
Reason(R): ab+ mode, if the file does not exist, it does not create a new file for reading and writing.
Ans: iii. A is True but R is False
Short Answer Questions
1. Write a python code to find the size of the file in bytes, number of lines and number of words.
# reading data from a file and find size, lines, words
f=open(‘Lines.txt’,’r’)
str=f.read( )
size=len(str)
print(‘size of file n bytes’,size)
f.seek(0)
L=f.readlines( )
word=L.split( )
print(‘Number of lines ’,len(L))
print(‘Number of words ’,len(word))
f.close( )
2. Write code to print just the last line of a text file “data.txt”.
Ans: fin=open(“data.txt”,”r”)
lineList=fin.readlines()
print(“Last line = “, lineList[-1])
3. Write a program to count the words “to” and “the” present in a text file “python.txt”.
Ans. fname = "python.txt"
num_words = 0
f= open(fname, 'r')
words = f.read().split()
for a in words:
if (a.tolower() == “to” or a.tolower() == “the” ):
num_words = num_words + 1
print("Number of words:", num_words)
f.close()
4. Write a program to display all the lines in a file “python.txt” along with line/record number.
Ans.
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
count=count+1
print(count,a)
fh.close()
5. Write a program to display all the lines in a file “python.txt” which have the word “to” in it.
Ans. fh=open("python.txt","r") c
ount=0
lines=fh.readlines()
for a in lines:
if (a.tolower().count(“to”) > 0) :
print(a)
fh.close()
6. Write a python program to create and read the city.txt file in one go and print the contents on the
output screen.
Answer: # Creating file with open() function
f=open("city.txt","w")
f.write("My city is very clean city.")
f.close() # Reading contents from city.txt file
f=open("city.txt","r")
dt = f.read()
print(dt)
f.close()
7. Consider following lines for the file friends.txt and predict the output:
Friends are crazy, Friends are naughty !
Friends are honest, Friends are best !
Friends are like keygen, friends are like license key !
We are nothing without friends, Life is not possible without friends !
f = open("friends.txt")
l = f.readline()
l2 = f.readline(18)
ch3=f.read(10)
print(l2)
print(ch3)
print(f.readline())
f.close()
Output:
Friends are honest
, Friends
are best !
Explanation: In line no. 2, f.readline() function reads first line and stores the output string in l but not
printed in the code, then it moves the pointer to next line in the file. In next statement we have
f.readline(18) which reads next 18 characters and place the cursor at the next position i.e. comma (,) , in
next statement f.read(10) reads next 10 characters and stores in ch3 variable and then cursor moves to
the next position and at last f.readline() function print() the entire line
8. Write a function count_lines() to count and display the total number of lines from the file. Consider
above file – friends.txt.
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
lines = f.readline()
print("no. of lines:",cnt)
f.close()
9. Write a function display_oddLines() to display odd number lines from the text file. Consider above file
– friends.txt.
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
lines = f.readline()
if cnt%2!=0:
print(lines)
f.close()
10. Write a function cust_data() to ask user to enter their names and age to store data in customer.txt file.
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()
Unit-1: File Handling – Binary, CSV Files (Questions)
Multiple Choice Questions
1. Out of the followings which mode is used for both reading and writing in binary format in file?
a) wb b) wb+ c) w d) w+
2. Which of the following is not true about binary files?
a) Binary files are store in terms of bytes
b) When you open binary file in text editor will show garbage values
c) Binary files represent ASCII value of characters
d) All of the above
3. What is the difference between wb and wb+ mode?
a) wb mode is used to open binary file in write mode and wb+ mode open binary file both for read
and write operation.
b) In wb mode file open in write mode and wb+ in read mode
c) File pointer is at beginning of file in wb mode and in wb+ at the end of file
d) No difference
4. The pickle module in Python is used for:
a) Serializing any Python object structure b) De-serializing Python object structure
c) Both a and b d) None of these
5. Which method is used to convert Python objects for writing data in binary file?
a) write() b) load() c) store() d) dump()
6. seek() function is used for _______.
a) positions the file object at the specified location.
b) It returns the current position of the file object
c) It writes the data in binary file
d) None of these
7. Which is not the valid mode for binary files?
a) r b) rb c) wb d) wb+
8. Which of the following function is used to read the data in binary file?
a) read() b) open() c) dump() d) load()
9. Suresh wants to open the binary file student.dat in read mode. He writes the following statement but he
does not know the mode. Help him to find the same.
F=open(‘student.dat’, ____)
a) r b) rb c) w d) wb
10. This method returns an integer that specifies the current position of the file object.
a) seek() b) load() c) position() d) tell()
11. Which of the following statement opens a binary file ‘test.bin’ in write mode and writes data from a
tuple t1=(2, 5, 8, 2) on the binary file?
(a) with open(‘test.bin’,‘wb’) as f: (b) with open(‘test.bin’,‘wb’) as f:
pickle.dump(f, t1) pickle.dump(t1,f)
(c) with open(‘test.bin’,‘wb+’) as f: (d) with open(‘test.bin’,‘ab’) as f:
pickle.dump(f,t1) pickle.dump(f,t1)
12. Which of the following character acts as default delimiter in a csv file?
a) (colon) : b) (hyphen) - c) (comma) , d) (vertical line) |
13. Which of the following is not a function / method of csv module in Python?
a) read() b) reader() c) writer() d) writerow()
Assertion Reason Questions
A. Both assertion and reason are true, and the reason is the correct explanation of the assertion.
B. Both assertion and reason are true, but the reason is not the correct explanation of the assertion.
C. Assertion is true, but the reason is false.
D. Assertion is false, but the reason is true.
1. Assertion (A): A binary file stores the data in the same way as stored in the memory.
Reason (R): Binary file in python does not have line delimiter Ans: B
2. Assertion (A): an open file can be close using close() function.
Reason (R): sometimes the data written onto files is held in memory until the file is closed. Ans: A
3. Assertion(A): pickle.dump() function is used to store the object data to the file.
Reason(R): Pickle.load() function is used to retrieve pickled data. Ans: B
4. Assertion(A): The seek(offset,from) method changes the current file position.
Reason(R): If from is 0, the beginning of the file to seek. If it is set to 1, the current position is used. If it
is set to 2 then the end of the file would be taken as seek position. The offset argument indicates the
number of bytes to be moved. Ans: A
5. Assertion(A): ab+ mode is used for both appending and reading binary files and move file pointer at end
Reason(R): ab+ mode, if the file does not exist, it does not create a new file for reading and writing.
Ans: C
Short Answer Questions
1. Identify the error in the following code:
import pickle
data=[‘one’, 2, [3, 4, 5]]
with open(‘data2.dat’, ‘rb’) as f:
pickle.dump(data, f)
Ans: The file is opened in read mode and dump() function tries to write onto file, hence there is error
line 3.
Correct code : with open(‘data2.dat’, ‘wb’) as f
2. Any recipe uses some ingredients. Write a program to store the list of ingredients in a binary file
recipe.dat.
Ans:
import pickle
ingredients= [‘cucumber’, ‘pumpkin’, ‘carrot’, ‘peas’]
with open(‘recipe.dat’, ‘wb’) as fout:
pickle.dump(ingredient, fout)
3. A binary file “student.dat” has structure [rollno, name, marks]. Write a user defined function
insertRec() to input data for a student and add to student.dat.
Ans:
import pickle
def insertRec():
f=open(‘student.dat’,’ab’)
rollno = int (input(‘Enter Roll Number :’))
name=input("Enter Name :")
marks = int(input(‘Enter Marks :’))
rec = [rollno, name, marks ]
pickle.dump( rec, f )
f.close()
4. A binary file “student.dat” has structure [rollno, name, marks]. Write a function searchRollNo( r ) in
python which accepts the student’s rollno as parameter and searches the record in the file
“student.dat” and shows the details of student i.e. rollno, name and marks (if found) otherwise shows
the message as ‘No record found’.
Ans:
def searchRollNo( r ):
f=open("student.dat","rb")
flag = False
while True:
try:
rec=pickle.load(f)
if rec[0] == r :
print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag == True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
5. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also display number of students scoring above 75%.
Ans:
import pickle
def CountRec():
f=open("STUDENT.DAT","rb")
num = 0
try:
while True:
rec=pickle.load(f)
if rec[2] > 75:
print(rec[0], rec[1], rec[2])
num = num + 1
except:
f.close()
return num
6. Abhay is a python learner. He created a binary file “Bank.dat” has structure as [account_no, cust_name,
balance]. He defined a function addfile( ) to add a record to Bank.dat. He also defined a function
CountRec( ) to count and return the number of customers whose balance amount is more than 100000.
He has some problem in the following codes.
import pickle
def addfile( ):
f = open('bank.dat', __________) #Statement1
acc_no = int(input('Enter account number: '))
cust_name = input('Enter name:')
bal = int(input('Enter balance'))
rec = ____________________ #Statement2
__________________ #Statement3
f.close()
def CountRec( ):
f = ________________ #Statement4
c=0
try:
while True:
rec = _______________ #Statement5
if rec[2] > 100000:
c += 1
except:
f.close()
return c
Answer questions (i)-(v) based on above case study.
(i). Help Abhay to complete the Statement1. Ans: f = open('bank.dat','wb')
(ii). How will he write the record in Statement2? Ans: rec = [acc_no, cust_name, bal]
(iii). What code will be there in Statement3 to write record in file? Ans: pickle.dump(rec, f)
(iv). Complete the Statement4 to open the file with correct mode. Ans: f = open('bank.dat','rb')
(v). What will be the Statement5? Ans: rec = pickle.load(f)
7. Write a python program to create a CSV file by entering user-id and password, read and search the
password for given user id.
import csv
with open("program.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue

8. Roshni of class 12 is writing a program in Python for her project work to create a CSV file “Teachers.csv”
which will contain information for every teacher’s identification Number , Name for some entries.She
has written the following code.However, she is unable to figure out the correct statements in few lines of
code,hence she has left them blank. Help her write the statements correctly for the missing parts in the
code.
Unit-1: Data Structures – Stack (Questions)
Multiple Choice Questions
1. Which end we use in stack to perform Push and Pop operation?
A. Front B. Rear C. Top D. Sop
2. Which principle followed by Stack?
A. FIFO B. LIFO C. FIOF D. TIPO
3. Which operation take place by stack?
A. Push B. Pop C. Traversal D. All of these
4. Which method we use to add an element in stack using list?
A. insert B. append C. add D. None of these
5. When we delete an element, the value of top will be
A. increment B. decrement C. Both A&B D. None of these
6. Process of inserting an element in stack is called _____________
a) Create b) Push c) Evaluation d) Pop
7. Process of removing an element from stack is called
a) Create b) Push c) Evaluation d) Pop
8. In a stack, if a user tries to remove an element from empty stack it is called _____________
a) Underflow b) Empty collection c) Overflow d) Garbage Collection
9. Pushing an element into stack already having five elements and stack size of 5, then stack becomes
a) Overflow b) Crash c) Underflow d) Userflow
10. Entries in a stack are “ordered”. What is the meaning of this statement?
a) A collection of stacks is sortable
b) Stack entries may be compared with the ‘<’ operation
c) The entries are stored in a linked list
d) There is a Sequential entry that is one by one
11. Which of the following applications may use a stack?
a) A parenthesis balancing program b) Tracking of local variables at runtime
c)Compiler Syntax Analyzer d) All of the mentioned
12. Sanya wants to remove an element from empty stack. Which of the following term is related to this?
(a) Empty Stack (b) Overflow (c) Underflow (d) Clear Stack
13. TRUE/FALSE:
1.LIFO stands for Last in First Out. (TRUE)
2. Can we perform Pop operation if stack is empty. (FALSE)
3. if size of stack is 5 can we Push 6 element in stack. (FALSE)
4. len() method used to find the size of stack. (TRUE)
5. Stack is a linear data structure. (TRUE)
Assertion Reason Questions
A. Both assertion and reason are true, and the reason is the correct explanation of the assertion.
B. Both assertion and reason are true, but the reason is not the correct explanation of the assertion.
C. Assertion is true, but the reason is false.
D. Assertion is false, but the reason is true.
1. ASSERTION (A): Using append(), many elements can be added at a time.
REASON(R): For adding more than one element, extend() method can be used. (D)
2. ASSERTION (A): LIFO is a technique to access data from queues.
REASON(R): LIFO stands for Last In First Out. (D)
3. ASSERTION (A): A Stack is a Linear Data Structure, that stores the elements in FIFO order.
REASON(R): New element is added at one end and element is removed from that end only. (D)
4. ASSERTION (A): An error occurs when one tries to delete an element from an empty stack.
REASON(R): This situation is called an Inspection. (C)
5. ASSERTION (A): A stack is a LIFO structure.
REASON (R): Any new element pushed into the stack always gets positioned at the index after the last
existing element in the stack. (B)

Short Answer Questions


1. Julie has created a dictionary containing names and marks as key value pairs of 6 students. Write a
program, with separate user defined functions to perform the following operations: -
• Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 75.
• Pop and display the content of the stack.
For example If the sample content of the dictionary is as follows: R={“OM”:76, “JAI”:45, “BOB”:89,
“ALI”:65, “ANU”:90, “TOM”:82}
The output from the program should be: TOM ANU BOB OM
ANSWER: R={'OM':76, 'JAI':45, 'BOB':89, 'ALI':65, 'ANU':90, 'TOM':82}
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[ ]:
return S.pop( )
else:
print('Underflow')
ST=[ ]
for k in R:
if R[k]>=75:
PUSH(ST,k)
while True:
if ST!=[ ]:
print (POP(ST), end=' ')
else:
break
2. Alarm has a list containing 10 integers. You need to help him create a program with separate user
defined functions to perform the following operations based on this list.
• Traverse the content of the list and push the even numbers into a stack.
• Pop and display the content of the stack.
For Example
If the sample content of the list is as follows:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output of the code should be: 38 22 98 56 34 12
ANSWER:
N=[12,13,34,56,21,79,98,22,35,38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[ ]:
return S.pop( )
else:
print('Underflow')
ST=[ ]
for k in N:
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[ ]:
print(POP(ST), end=" ")
else:
break
3. 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.
• 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.
• 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.
ANSWER:
travel=[]
def Push_element(NList):
for L in NList:
if(L[1] != 'India' and L[2]<3500):
travel.append([L[0],L[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print('Stack Empty')
Unit-2: Computer Networks and Communication (Questions)
Multiple Choice Questions
1. ARPANET stands for-
(a) Advanced Real Projects Air Network
(b) Advanced Research Preparation Agency Network
(c) Advanced Recruitment Process Agency Network
(d) Advanced Research Projects Agency Network
2. In 1990s, the internetworking of which three networks resulted into Internet?
(a) WWW, GPS and other private networks (b) ARPANET, NSFnet and other private networks
(c) ARPANET, NSFnet and other public networks (d) ARPANET, GPS and NSFnet
3. The combination of two or more interconnected networks is called
a)Internetwork b) LAN c) MAN d) WAN
4. ISP stands for
a) International Service Provider b) International System Provider
c) Internet Service Provider d) Internetwork System Provider
5. Which one is not a part of data communication?
a. Sender b. Receiver c. Message d. Protocol e. None of these
6. _______________ is a globally existing network of networks consisting of a huge number of computers
situated in all the parts of the world?
A) Computer Network B) Intranet C) Internet D) All of the above
7. With the use of computer network, we can share:
(a) Data (b) Resources (c) Both of the above (d) None of the above
8. Correct unit of data transfer rate in communication is /are :
a) Kbps b) Mbps c) Gbps d) All of the above
9. In a network 32 Kb of data can be transferred per second what is the bandwidth of this network:
a) 32 Kbps b) 32KBps c) 32Kbps d) 32Kbpm
10. What is the meaning of bandwidth in a network?
a. Class of IP used in network b. Connected computers in a network
c. Transmission capacity of a channel. d. None of the above .
11. XYZ company is planning to link its head office situated in New Delhi with the offices in hilly areas.
Suggest a way to connect it economically:
a. Micro wave b. Coaxial cable c. Fibre optic d. Radio wave
12. Which of the following is/are not communication media?
a. Microwave b. Optical Fiber cable c. Node d. Radio wave
13. The other name for communication medium is:
a. Channel b. Source c. Hub d. Switch
14. What is the channel that communicates and carries information from the sender to the receiver?
a. Transmission media b. Sender media c. Receiver media d. a & b
15. In data communications, transmission medium is the path established between ____________?
a. Sender and Receiver b. Source and Destination
c. Server and Client d. All Mentioned Above
16. In _____________network, bits are transmitted as pulses of light?
a. Fibre Based Network b. Copper Based Network
c. Radio-waves Based Network d. All Mentioned Above
17. Transmission Media is classified as ____________?
a. Unguided b. Guided c. Direct d. a & b both
18. Physical medium to transmit signals is present in _____________?
a. Unguided b. Guided c. Direct d. Indirect
19. Which of the following connector is used to attach the ethernet cable?
a. RC Connector b. T Connector c. RJ45 Connector d. E Connector
20. The modem at the sender’s computer end acts as a ____________.
a. Model b. Modulator c. Demodulator d. Convertor
21. Which one of the following network devices is the broadcast device?
a. Hub b. Router c. Switch d. None of the above
22. Which one of the following network devices is used to create a network?
a. Hub b. Switch c. Router d. All of the above
23. Which one of the following network devices can work with similar networks?
a. Router b. Gateway c. Both a and b d. None of the above
24. Which of the following device an interface between computer and network?
a. Modem b. Router c. Ethernet Card d. Repeater
25. Which one of the following network devices is not an intelligent device?
a. Hub b. Switch c. Router d. None of the above
26. The function of a repeater is to take a weak and corrupted signal and it.
a) Restore. b) Regenerate. c) Amplify. d) Reroute
27. Which type of network consists of both LANs and MANs?
a. Wide Area Network b. Local Area Network c. Both a and b d. None of the above
28. Physical or Logical arrangement of network is called
a) Networking b) Topology c) Routing d) Control
29. What is the purpose of a modem in a computer network?
a) To connect devices within a local area network
b) To transmit data over long distances using radio waves
c) To convert digital signals to analog signals and vice versa
d) To route data packets between different networks
30. Which network topology connects all devices in a linear fashion?
a) Bus b) Star c) Tree d) Mesh
31. Which network type covers a small geographical area, like an office or a building?
a) PAN b) LAN c) MAN d) WAN
32. Which network topology connects all devices to a central hub?
a) Bus b) Star c) Tree d) Mesh
33. A computer network created by connecting the computers of your school‟s computer lab is an example
of
a)LAN b) MAN c) WAN d) PAN
34. Which service/protocol out of the following will be most helpful to conduct live interactions of
employees from Mumbai Branch and their counterparts in Texas ?
(i) FTP (ii) PPP (iii) SMTP (iv) VolP
35. Identify the protocol primarily used for browsing data.
(A)FTP (B)TCP (C) SMTP (D)HTTP
36. POP3 is a protocol used for ______
(A)Reading protocols (B)Acessing emails 69
(C)Downloading images from the server (D)Downloading emails
37. SMTP is used for
(A)Adding address to emails. (B)Connecting with server
(C)Sending emails from one server to another. (D)Downloading emails
38. The protocol suit that is the main communication protocol of over the internet
(A)HTTP (B)FTP C) TCP/IP (D)PPP
39. What does WWW stand for?
A) World Web Web B) Web World Wide C) World Wide Web D) Wide World Web
40. Which markup language is used for creating the structure of web pages?
A) CSS B) HTML C) XML D) JavaScript
41. Which markup language is primarily used for defining data structures and encoding data?
A) HTML B) CSS C) XML D) JavaScript
42. Which markup language is primarily used for defining data structures and encoding data?
A) HTML B) CSS C) XML D) JavaScript
43. What is the primary function of a domain name?
A) To specify the web server's IP address B) To define the path to a web page
C) To store web content D) To serve as a web browser
44. What part of a URL typically follows the domain name and identifies the specific resource on a website?
A) Protocol B) Port C) Query string D) Path
45. What is a website composed of?
A) Web browsers only B) Web servers only
C) Web browsers and web servers D) Domain names only
46. Which software application is used to access and view web pages on the internet?
A) Web server B) HTML editor C) Web browser D) Web host
47. What is the primary function of a web server in the context of the World Wide Web?
A) Rendering web pages B) Storing web content
C) Accessing domain names D) Hosting websites
48. What service does a web hosting provider offer?
A) Domain registration B) Creating web content
C) Storing and serving web content D) Web browsing
49. Which of the following components is NOT part of a URL?
A) Protocol B) Domain name C) Port number D) File extension

Short Answer Questions


1. Nidhi is confused between bandwidth and data transfer rate . Help her to understand the same .
Bandwidth Data transfer rate
Difference in highest and lowest frequency of No. of bits transferred per unit of time
signals in a network
Unit : Htz Unit : Mbps , Kbps
2. Expand the following :
1. Kbps 2. Mbps 3. Gbps 4. Bps
Ans: Kilobits per second , Megabits per second , Gigabits per second , bits per second.
3. Your friend wishes to install a wireless network in his office. Explain him the difference between guided
and unguided media.
Answer: Guided media uses cables to connect computers. It is also referred to as Wired or Bounded
transmission media. Signals being transmitted are directed and confined in a narrow pathway by using
physical links.
In wireless communication technology, information travels in the form of electromagnetic signals
through air. Wireless technologies allow communication between two or more devices in short to long
distance without requiring any physical media.
4. Rearrange the following terms in increasing order of speedy medium of data transfer:
Telephone line, Fiber Optics, Coaxial Cable, Twisted Paired Cable.
Answer: Telephone line, Twisted Pair Cable, Coaxial Cable, Fiber Optics.
5. Give two examples of each – Guided media and Unguided media.?
Answer: Guided – Twisted pair, Coaxial Cable, Optical Fiber (any two)
Unguided – Radio waves, Satellite, Micro Waves (any two)
6. Why is switch called an intelligent hub?
ANS- Switch is used to connect multiple computers or communicating devices within a office /building
thus creating LANs.. When data arrives, the switch extracts the destination address from the data packet
and looks it up in a table to see where to send the packet. Thus, it sends signals to only selected devices
instead of sending to all.
7. What is the difference between a Hub and Switch?
Hub Switch
It broadcast signals to all the devices connected it sends signals to only selected devices instead of
sending to all
It is not an intelligent device it is an intelligent device
Hub is simply old type of device and is not switch is very sophisticated device and widely
generally used used.
8. What is HTTPs and what port does it use?
Answer: HTTPs is a Secure HTTP. HTTPs is used for secure communication over a computer network.
HTTPs provides authentication of websites that prevents unwanted attacks. In bi-directional
communication, the HTTPs protocol encrypts the communication so that the tampering of the data gets
avoided. With the help of an SSL certificate, it verifies if the requested server connection is a valid
connection or not. HTTPs use TCP with port 443.
9. Expand the following: SMTP, PPP
Answer: SMTP-Simple Mail Transfer Protocol PPP- Point to point protocol
10. Write short Notes on a) POP3 b) SMTP.
a) Post Office Protocol version 3 (POP3) is a standard mail protocol used to receive emails from a remote
server to a local email client. POP3 allows you to download email messages on your local computer and
read them even when you are offline. Note, that when you use POP3 to connect to your email account,
messages are downloaded locally and removed from the email server
b) Simple Mail Transfer Protocol (SMTP) is the standard protocol for sending emails across the Internet.
By default, the SMTP protocol works on these ports:
11. Compare between HTTP and HTTPS.
Answer : The only difference between the two protocols is that HTTPS uses TLS (SSL) to encrypt normal
HTTP requests and responses, and to digitally sign those requests and responses. As a result, HTTPS is far
more secure than HTTP
12. What is the World Wide Web (WWW), and how does it differ from the internet as a whole?
Answer: The World Wide Web (WWW or Web) is a system of interconnected documents and resources
linked via hyperlinks and URLs (Uniform Resource Locators). It is a subset of the internet that primarily
consists of web pages and multimedia content. The internet, on the other hand, is a global network that
encompasses various services, including email, file sharing, and more. The WWW is just one of many
services offered on the internet.
CASE STUDY BASED Qs
NETWORKING
CLASS 12th CS/IP
LOVEJEET ARORA
Question 1:
Tagore School, in Jaipur is starting up the network between its different wings. There are four
Buildings named as SENIOR, JUNIOR, ADMIN and HOSTEL as shown below:

SENIOR JUNIOR

HOSTEL ADMIN

The distance between various buildings

Number of Computers in Each Building


ADMIN TO SENIOR 200 M
ADMIN TO HOSTEL 50 M
SENIOR 130
ADMIN TO JUNIOR 150 M JUNIOR 80
JUNIOR TO HOSTEL 340 M HOSTEL 50
SENIOR TO HOSTEL 300 M ADMIN 160
SENIOR TO JUNIOR 250 M

(i) Suggest the cable layout of connections between the buildings.


(ii) Suggest the most suitable place (i.e., building) to house the server of this school, provide a
suitable reason.
(iii) Suggest the placement of the following devices with justification.
o Repeater
o Hub/Switch
(iv) The organisation also has inquiry office in another city about 50-60 km away in hilly region.
Suggest the suitable transmission media to interconnect to school and inquiry office out of the
following :
o Fiber optic cable
o Microwave
o Radiowave

Answer 1:

(i)
(ii) Server can be placed in the ADMIN building as it has the maxium number of computer.
(iii) Repeater can be placed between ADMIN
and SENIOR building as the distance is more than 110 m.
(iv) Radiowaves can be used in hilly regions as they can travel through obstacles.

Question 2:
Good Marks Public School in Shimla is setting up the network between its different wings. There
are 4 wings named as SENIOR(S), JUNIOR(J), ADMIN(A) and HOSTEL(H).
Distance between various wings: Number of Computers in each Wing

Wing A to Wing S 100 m Wing Number of


Wing A to Wing J 200 m Computers
Wing A to Wing H 400 m Wing A 20
Wing J to Wing H 450 m
Wing S 150
Wing S to Wing H 100 m
Wing S to Wing J 300 m Wing J 50
Wing H 25
(i) Suggest a suitable Topology for networking the computers of all wings.
(ii)Name the most suitable wing where the Server should be installed. Justify your answer.
(iii)Suggest where all should Hub(s)/Switch(es) be placed in the network.
(iv)Which communication medium would you suggest to connect this school with its main branch
in Delhi ?
Answer 2:

(i)
(ii) Server should be in Wing S as it has the maxi-mum number of computers.
(iii) All Wings need hub/switch as it has more thanone computer.
(iv) Since the distance is more, wireless transmission would be better. Radiowaves are reliable
and can travel through obstacles.
Question 3:
Star Info Solution is a professional consultancy company. The company is planning to set up their
new offices in India with its hub at Jaipur. As a network adviser, you have to understand their
requirement and suggest them the best available solutions. Their queries are mentioned as (i) to
(iv) below.
Physical Locations of the blocked of Company

(i) What will be the most appropriate block, where company should plan to install their
server?
(ii) Draw a block to cable layout to connect all the buildings in the most appropriate manner for
efficient communication.
(iii) What will be the best possible connectivity out of the following, you will suggest to connect
the new setup of offices in Bangalore with its London based office:
o Satellite Link
o Infrared
o Ethernet Cable
(iv) Which of the following device will be suggested by you to connect each computer in each of
the buildings:
o Switch
o Modem
o Gateway
Answer 3:

(i) Finance block because it has maximum


number of computers.

(ii)
(iii) Satellite link
(iv) Switch

Question 4:
Rehaana Medicos Center has set up its new center in Dubai. It has four buildings as shown in the
diagram given below:
Accounts Research Packaging Store
LAb Unit

As a network expert, provide the best possible answer for the following queries:
(i) Suggest a cable layout of connections between the buildings.
(ii) Suggest the most suitable place (i.e. building) to house the server of this organization.
(iii) Suggest the placement of the following device with justification:
(iv) Repeater (b) Hub/Switch
(v) Suggest a system (hardware/software) to prevent unauthorized access to or from the
network.

Answer 4:
(i) Layout 1
(ii) The most suitable place / building to house the server of this organization would be building
Research Lab, as this building contains the maximum number of computers.
(iii) Since the cabling distance between Accounts to Store is quite large, so a repeater would
ideally be needed along their path to avoid loss of signals during the course of data flow in
this route.
(iv) Firewall.
Question 5:
1. Expert Professional Global (EPG) is an online, corporate training provider company for IT
related courses. The company is setting up their new campus in Mumbai. You as a network
expert have to study the physical locations of various buildings and the number of
computers to be installed. In the planning phase, provide the best possible answer for the

Building to Building distances (in Mtrs.)

(i) Suggest the most appropriate building, where EPG should plan to install the server.
(ii) Suggest the most appropriate building to building cable layout to connect all three buildings
for efficient communication.
(iii) Which type of network out of the following is formed by connecting the computers of these
three buildings?
o LAN
o MAN
o WAN
(iv) Which wireless channel out of the following should be opted by EPG to connect to students
of all over the world?
o Infrared
o Microwave
o Satellite

nswer 5:
(i) Faculty Studio Building
(ii) Bus Topology
(iii) LAN
(iv) Satellite

Question 6:
“Learn India” is a skill development community which has an aim to promote the standard of skills
in the society. It is planning to set up its training centres in multiple towns and villages Pan India
with its head offices in the nearest cities. They have created a model of their network with a city
ABC Nagar, a town (UVW town) and 3 villages.
As a network consultant, you have to suggest the best network related solutions for their issues/
problems raised in (i) to (iv), keeping in mind the distances between various locations and other
given parameters.

Note:
– In Villagers, there are community centers, in which one room has been given as training entrer
to this organization to install computers.
– The organization has got financial support from the government and top Multinational Organi-
zations.
(i) Suggest the most appropriate location of the SERVER in the Cluster (out of the 4 locations),
to get the best and effective connectivity. Justify your answer.
(ii) Suggest the best wired medium and draw the cable layout (location to location) to efficiently
connect various locations within the Cluster.
(iii) Which hardware device will you suggest to connect all the computers within each location of
(iv) Which service/protocol will be most helpful to conduct live interactions of Expersts from
Head Office and peole at all locations of Cluster?

Answer 6:
(i) Best location for the server is UVW-TOWN, because it is approximately equidistant from
the village P, Q and R.
(ii) For connectivity between UVW-TOWN to head office is optic Fiber and to connect the
villages, P, Q and R with server at UVW- TOWN is co-axial cable.
(iii) The villages R Q and R can be connected with server at UVW-TOWN by a Hub and the head
office is connected by a Bus topology.
(iv) Between head office and UVWTOWN
we recommend for Bus topology, so HTTP protocol and other terminal can be connected by
UDP or FTP protocols.
Question 7:
Raj IT Solutions located in the hilly area of Nanital. The companies are located in four different,
blocks whose layout is shown in the following figure. Answer the questions (i) to (iv) with the
relevant justifi-cations.

Distance between various Blocks : Number of Computers in each Wing

Block A to Block C 50 m
Wing Number of
Block A to Block D 100 m
Computers
Block B to Block C 40 m
Block A 25
Block B to Block D 70 m
Block B 50
Block C to Block D 125 m
Block C 20
Block A to Block B 75 m
-
Block D 120
(i) Suggest a suitable network topology between the blocks.
(ii) Which is the most suitable block to house the server of this organization?
(iii) Suggest the placement of the following devices with justification
o Repeater
o Switch
(iv) The organization is planning to link the whole blocks to its marketing Office in Delhi. Since
cable connection is not possible from Shimla, suggest a way to connect it with high speed.
Answer 7:
(i) Suitable topology is bus topology.
(ii) The most suitable block for hosting server is BLOCK-D because this block has maximumnumber
of computers.
(iii) Switch is a device used to segment network into different sub-networks so switch will existin all the
blocks. Since distance between BLOCK-D and BLOCK-C is large so repeater will beinstall between
BLOCK-D and BLOCK-C.
(iv) The most economic way to connect it with a reasonable high speed would be the use radiowave
transmission, as they are easy to install, can travel long distance and penetrate buildings easily, so
they are used for communication, both indoors and outdoors. Radiowaves also have the
advantage of being omni-directional. They can travel in all the directions from the source, so that
the transmitter and receiver do not have to be carefullyaligned physically.
Question 8:
Zigma Institute is planning to set up its center in Bikaner with four specialized blocks for Medicine,
Management, Law courses along with an Admission block in separate buildings. The physical
distances between these blocks and the number of computers to be installed in these blocks are
given below. You as a network expert have to answer the queries raised by their board of directors
as given in (i) to (iv).

Admin Managemen Medicine


Law

distances between various locations in meters:

Admin Block to Management Block 60


Admin Block to Medicine Block 40
Admin Block to Law Block 60
Management Block to Medicine Block 50
Management Block to Law Block 110
Law Block to Medicine Block 40

Number of Computers installed at various locations:


Admin Block 150
Management Block 70
Medicine Block 20
Law Block 50

(i). Suggest the most suitable location to install the main server of this institution to get efficient
connectivity.
(ii). Suggest by drawing the best cable layout for effective network connectivity of the blocks
having server with all the other blocks.
(iii). Suggest the devices to be installed in each of these buildings for connecting computers
installed within the building out of the following:
• Modem
• Switch
• Gateway
• Router
(iv) Suggest the most suitable wired medium for efficiently connecting each computer installed in
every building out of the following network cables:
• Coaxial Cable
• Ethernet Cable
• Single Pair
• Telephone Cable.
Answer 8:
i) Admin Block
(ii)
(iii) Modem or Switch or Router
(iv)Ethernet Cable
Question 9:
Knowledge Supplement Organisation has set up its new centre at Mangalore for its office and web
based activities. It has 4 blocks of buildings as shown in the diagram below:

Block

C
Block Block
A
D
Block

distances between various blocks Number of Computers


Black A to Block B 50 m Black A 25
Block B to Block C 150 m Block B 50
Block C to Block D 25 m Block C 125
Block A to Block D 170 m Block D 10
Block B to Block D 125 m
Block A to Block C 90 m
(i) Suggest a cable layout of connections between the blocks.
(ii) Suggest the most suitable place (i.e. block) to house the server of this organization with a
suitable reason.
(iii) Suggest the placement of the following devices with justification
(a) Repeater
(b) Hub/Switch
(iv) The organization is planning to link its front office situated in the city in a hilly region where
cable connection is not feasible, suggest an economic way to connect it with reasonably high
speed?
Ans 9 : (i)
Block
Block
A
Block
Block

(ii) The most suitable place / block to house the server of this organisation would be Block C, as
this block contains the maximum number of computers, thus decreasing the cabling cost for most
of the computers as well as increasing the efficiency of the maximum computers in the network.

(iii) (a) For Layout 1, since the cabling distance between Blocks A and C, and that between B and
C are quite large, so a repeater each, would ideally be needed along their path to avoid loss of signals
during the course of data flow in these routes.

(b) A hub/switch each would be needed in all the blocks, to interconnect the group of cables from
the different computers in each block.

(iv)The most economical way to connect it with a reasonable high speed would be to use radio wave
transmission, as they are easy to install, can travel long distances, and penetrate buildings easily, so
they are widely used for communication, both indoors and outdoors. Radio waves also have the
advantage of being omni directional, which is they can travel in all the directions from the source,
so that the transmitter and receiver do not have to be carefully aligned physically.
Question 10:

Gyan Vidya Bharti in Srinagar is setting up the network between its different wings. There are 4
wings named as SENIOR(S), MIDDLE(M), JUNIOR(J) and OFFICE(O).
Distance between the various wings are given below: Number of Computers

Wing O to Wing S 100m Wing O 10


Wing O to Wing M 200m Wing S 200
Wing O to Wing J 400m Wing M 100
Wing S to Wing M 300m Wing J 50
Wing S to Wing J 100m
Wing J to Wing M 450m
(i) Suggest a suitable Topology for networking the computer of all wings.
(ii) Name the wing where the server to be installed. Justify your answer.
(iii) Suggest the placement of Hub/Switch in the network.
(iv) Mention an economic technology to provide internet accessibility to all wings.

Ans10:
• Star or Bus or any other valid topology.
• Wing S, because maximum number of computers are located at Wing S.
• Hub/ Switch in all the wings.
• Coaxial cable/Modem/LAN/TCP-IP/Dialup/DSL/Leased Lines or any other
validtechnology.
Unit-3: Database concepts and the Structured Query Language
Database: A database is a collection of DATA/INFORMATION that is organized so that it can be easily accessed,
managed and updated. In Database, Data is organized into rows, columns and tables.

Why Do We Need Database?


• To manage large chunks of data
• Accuracy
• Ease of updating data
• Security of data
• Data integrity
Database Management System (DBMS): A DBMS refers to software that is responsible for storing, maintaining and
utilizing database in an efficient way. Examples of DBMS software are Oracle, MS SQL Server, MS Access, Paradox,
DB2 and MySQL etc. MySQL is open source and freeware DBMS.

Advantages of Database System:


• Databases reduces Redundancy
• Database controls Inconsistency
• Database facilitate Sharing of Data
• Database ensures Security
• Database maintains Integrity

Data Model- Way of data representation


• Relational Data Model
• Network Data Model
• Hierarchical Data Model
• Object Oriented Data Model

Relational Database: A relational database is a collective set of multiple data sets organized by tables, records and
columns. A Relational database use Structured Query Language (SQL), which is a standard user application that
provides an easy programming interface for database interaction.

Relation (Table) - A Relation or Table is Matrix like structure arranged in Rows and Columns.
Domain - It is collection of values from which the value is derived for a column.
Tuple / Entity / Record - Rows of a table is called Tuple or Record.
Cardinality - Number of rows (Records) in a table.
Attribute/ Field - Column of a table is called Attribute or Field.
Degree - Number of columns (attributes) in a table.
KEYS IN A DATABASE: Key plays an important role in relational database; it is used for identifying unique rows from
table & establishes relationship among tables on need.

Types of keys in DBMS


• Candidate Key – It is an attribute uniquely identify each record in that table.
• Primary Key – A primary is a column that uniquely identifies tuples (rows) in that table.
• Alternate Key – Out of all candidate keys, only one gets selected as primary key, remaining keys are known
as alternate or secondary keys.
• Foreign Key – Foreign keys are the columns of a table that points to the primary key of another table. They
act as a cross-reference between tables.

SQL - is an acronym of Structured Query Language. It is a standard language developed and used for accessing and
modifying relational databases.
SQL is being used by many database management systems. Some of them are:
➢MySQL ➢PostgreSQL ➢Oracle ➢SQLite ➢Microsoft SQL Server
MySQL is currently the most popular open-source database software. It is a multi-user, multithreaded database
management system.

Types of SQL Commands


• DDL (Data Definition Language) To create database and table structure-
o commands like CREATE , ALTER , RENAME, DROP etc.
• DQL (Data Query Language) To retrieve the data from database SELECT
• DML (Data Manipulation Language) Record/rows related operations.
o commands like INSERT, DELETE, UPDATE etc.

MySql datatypes: int, float(x,y), char(x), varchar(x), date(yyyy-mm-dd), etc..

Constraints: Constraints are certain types of restrictions on the data values that an attribute can have.
Types of Constraints:
• NOT NULL - Ensures that a column cannot have NULL values where NULL means missing / unknown / not
applicable value.
• UNIQUE - Ensures that all the values in a column are distinct /unique.
• PRIMARY KEY - The column which can uniquely identify each row or record in a table.
MULTIPLE CHOICE QUESTIONS
1. What is a database?
(A) A collection of organized data (B) A software program used to manage data
(C) A hardware device used to store data (D) All of the above

2. What are the benefits of using a database?


(A) Improved data organization and efficiency (B) Reduced data redundancy
(C) Improved data integrity (D) Improved data security (E) All of the above
3. What is the relational data model?
(A) A type of database model that stores data in tables
(B) A type of database model that stores data in hierarchies
(C) A type of database model that stores data in networks
(D) All of the above
4. What is a relation in the relational data model?
(A) A table (B) A row in a table (C) A column in a table (D) None of the above
5. What is an attribute in the relational data model?
(A) A column in a table (B) A row in a table (C) A table (D) None of the above
6. What is the domain of an attribute?
(A) The set of possible values that the attribute can take (B) The name of the attribute
(C) The data type of the attribute (D) None of the above
7. What is the degree of a relation?
(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above
8. What is the cardinality of a relation?
(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above
9. What is a key in the relational data model?
(A) A set of attributes that uniquely identifies a tuple in a relation
(B) A set of attributes that is used to sort the tuples in a relation
(C) A set of attributes that is used to filter the tuples in a relation
(D) None of the above

10. What is a foreign key in the relational data model?


(A) A set of attributes in one relation that references the primary key of another relation
(B) A set of attributes in one relation that references the candidate key of another relation
(C) A set of attributes in one relation that references the foreign key of another relation
(D) None of the above

ASSERTION REASONING QUESTIONS


1. Assertion (A): A database is a collection of organized data.
Reason (R): A database can be used to store a wide variety of data types, including text, numbers, images,
and videos.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).
2. Assertion (A): The relational data model is a type of database model that stores data in tables.
Reason (R): The relational data model is the most popular type of database model used today.
Answer: Both (A) and (R) are correct and (R) is not the correct explanation of (A).
3. Assertion (A): A relation in the relational data model is a set of tuples.
Reason (R): A tuple is a column in a table.
Answer: Assertion (A) is True and Reason (R) is False.
4. Assertion (A): A foreign key in the relational data model is a set of attributes in one relation that
references the primary key of another relation.
Reason (R): Foreign keys are used to establish relationships between tables.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).
5. Assertion (A): A candidate key in the relational data model is a set of attributes that uniquely identifies a
tuple in a relation.
Reason (R): A primary key is a candidate key that is chosen to be the unique identifier for tuples in a
relation.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).

SQL – DDL Commands: Create, Alter, Rename, Drop (CARD)


Create Command -DDL
To Create a Database
Create database Mydatabase;
To use Database
Use Mydatabase;
To see the list of Databases
Show databases;
To see the list of tables
Show tables;
Create table
Create table class12
(
Roll int,
Name varchar(20),
Gender char(1),
Marks float(4,2),
City varchar(20),
DoB date
);
To describe TABLE/ To see the structure of a table
Desc class12;
Describe class12;
Q1: Write a SQL statement to create a simple table
Countries(country_id, country_name and region_id)
BankRecords(AccountNo, Name, Gender, DoB, Address, Balance)
Alter Command - DDL
Create database kvtezu;
Use kvtezu;
Create table class11
(
RollNo int,
Name varchar(20)
);
Desc class11;
1.Add new column
Alter table class11 add Marks float(4,2);
Alter table class11 add column city varchar(20);
Desc class11;
2.Add Primary key
Alter table class11 add Primary key(RollNo);
3. Drop Primary key column
Alter table class11 DROP primary key;
4. Drop a column
Alter table class11 DROP city;

DROP Command – DDL


1.Drop Table
Drop table class11;
Show tables
2.Drop Database;
Drop databse Mydatabase;

SQL – DML Commands– SELECT, INSERT, DELETE, UPDATE


Create Table
Create table class11
(
Rollno int primary key,
Name varchar(20),
Marks float(4,2),
City varchar(20)
);
INSERT COOMAND - DML
1.Insert a single row
Insert into class11 values(101,”Virat”,96.45,”Delhi”);
Select * from class11;
2.insert multiple rows
Insert into class11 values
(102,”Rohit”,95.34,”Mumbai”),
(103,”Shubman”,93,”Kolkata”),
(104,”Jaiswal”,90,”Mumbai”),
(105,”Shami”,93.50,”Kolkata”),
(106,”Bumrah”,95.65,”Gujrat”),
(107,”Kuldeep”,93,”UP”),
(108,”Jadeja”,92,”Gujrat”)
);
Select * from class11;
3.insert in specific column
Insert into class11 (Rollno, Name) values(109,”Dhoni”);
4.insert null values
Insert into class11 values(110,Null,NULL,”Kolkata”);
5.insert date dddd-mm-dd
Alter table class11 ADD Entrydate date;
Insert into class11 values(111,”Harshal”,NULL,”Kolkata”,”2022-2-1”);
6.insert time hh:mm:ss
Alter table class11 ADD EntryTime time;
Insert into class11 values(112,”Patel”,94,”Delhi”,”10:30”2022-2-1”);
SELECT COMMAND –DML
1. To display complete Table
Select * from class11;
2.To display a particular column
Select Name from class12;
Select Name, City from class11;

UPDATE COMMAND – DML


UPDATE TableName SET attr=attrChange WHERE Cond;
1. update the time in table class11;
UPDATE class11 SET EntryTime=”10:30”;
UPDATE class11 SET Marks=90 WHERE RollNo=109;

DELETE COMMAND – DML


DELETE FROM Tablename WHERE Cond;
Delete from class11 where Marks is NULL;
Delete from class11 where City=”Delhi”;
Delete from class11;
Desc class11;

MULTIPLE CHOICE QUESTIONS


1. In a table STUDENT in MySQL database, an attribute NAME of data type VARCHAR(20) has the value
“ASEEMA SAHU”. Another attribute SUBJECT of data type CHAR(10) has value “CS”. How many
characters are occupied by attribute NAME and attribute SUBJECT respectively?
A. 11, 10 B. 11, 2 C. 12, 3 D. 20, 10
2. Identify the MySQL Commands that belongs to DML category:
A. ALTER B. DROP C. DELETE D. CREATE
3. Consider the following Statements : Statement – 1 : UNIQUE constraint ensures that all the values in a
column are distinct / unique. Statement – 2 : MySQL is an open-source relational database
management system.
A. Only Statement-1 is True B. Only Statement-2 is True
C. Both Statements are True. D. Both Statements are False.
4. Fill in the blank:
_____________________________ are used to define the different structures in a database.
A. Data Definition Language (DDL) Statement B. Data Manipulation Language (DML) Statement
C. Transaction Control Statement D. Session Control Statement
5. Naresh wants to create an attribute for admission number. Which will be the most suitable data type
for admission number which can accommodate admission numbers with 4 digits?
A. VARCHAR(2) B. CHAR(3) C. INT D. DATE
6. “The column which can uniquely identify each row or record in a table.”
The above Statement refers to which constraints in MySQL?
A. NOT NULL B. UNIQUE C. PRIMARY KEY D. DEFAULT
7. Identify the Statement which is NOT CORRECT?
A. It is mandatory to define constraint for each attribute of a table.
B. Constraints are certain types of restrictions on the data values that an attribute can have.
C. Constraints are used to ensure the accuracy and reliability of data.
D. It is not mandatory to define constraint for each attribute of a table.
8. Choose the correct MySQL statement to create a database named TARGET100.
A. CREATE TARGET100;
B. CREATE DATABASE TARGET100;
C. CREATE DATABASES TARGET100;
D. Database TARGET100 is not a valid database name. Hence, it cannot be created.
9. Prapti is presently working in the database SUBJECT. She wants to change and go to the database
RECORD. Choose the correct statement in MySQL to go to the database RECORD.
A. GO TO DATABASE RECORD; B. USE DATABASE RECORD;
C. CHANGE DATABASE RECORD D. USE RECORD;
10. Smiti has entered the following statements in MySQL. But it shows an error as mentioned below. Help
her to identify the reason for such error?
mysql> CREATE TABLE PRACTICAL(
-> SUBJECT VARCHAR(20),
-> MARKS INT,
-> ROLL INT,
-> NAME VARCHAR(30));
ERROR 1046 (3D000): No database selected
A. She has to first USE an available database or create a new database and then USE it.
B. Wrong syntax for CREATE TABLE
C. Wrong data type declaration
D. PRACTCAL named table already exists.
11. Which of the following statements will delete all rows in a table namely mytable without deleting the
table’s structure?
a. DELETE From mytable; b. DELETE TABLE mytable;
c. DROP TABLE mytable; d. None of these
12. Consider following SQL statement. What type of statement is this?
DELETE FROM employee;
a) DML b) DDL c) DCL d) Integrity constraint

Short Answer Type Questions


1. Write MySQL statements for the following:
i. To create a database named SCHOOL.
ii. To create a table named REMEDIAL based on the following specification:
Field Datatype Constraints
SNAME VARCHAR( 20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY
Answer:
i. CREATE DATABASE SCHOOL;
ii. CREATE TABLE REMEDIAL (
SNAME VARCHAR(20) NOT NULL,
ROLL INT UNIQUE,
FEES FLOAT ADMN INT PRIMARY KEY);
2. Mr. Kareem Sen has just created a table named “STUDENT” containing columns SNAME, SUBJECT and
FEES. After creating the table, he realized that he has forgotten to add a PRIMARY KEY column in the
table. Help him in writing an SQL command to add a PRIMARY KEY column ADMN of integer type to
the table Employee.
Answer: ALTER TABLE STUDENT ADD ADMN INT PRIMARY KEY;
3. Zenith is working in a database named SCHOOL, in which she has created a table named “STUDENT”
containing columns ADMN, SNAME, GENDER and CATEGORY. After creating the table, she realized
that the attribute, GENDER has to be deleted from the table and a new attribute FEES of data type
FLOAT has to be added. This attribute FEES cannot be left blank. Help Zenith to write the commands to
complete both the tasks.
Answer:
ALTER TABLE STUDENT DROP GENDER;
ALTER TABLE STUDENT ADD FEES FLOAT NOT NULL;
4. (i) State one difference between DDL and DML statements in MySQL.
(ii) Write the MySQL statement to delete the database named “SCHOOL”.
Answer:
i. DDL (Data Definition Language): DDL statements are used to create structure of a table, modify the
existing structure of the table and remove the existing table.
DML (Data Manipulation Language): DML statements are used to access and manipulate data in
existing tables which includes inserting data into tables, deleting data from the tables, retrieving data
and modifying the existing data.
ii. DROP DATABASE SCHOOL;
5. Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP
Answer: DDL - ALTER, DROP DML - INSERT, UPDATE

6. In a multiplex, movies are screened in different auditoriums. One movie can be shown in more than
one auditorium. In order to maintain the record of movies, the multiplex maintains a relational
database consisting of two relations viz. MOVIE and AUDI respectively as shown below:
Movie(Movie_ID, MovieName, ReleaseDate)
Audi(AudiNo, Movie_ID, Seats, ScreenType,TicketPrice)
a) Is it correct to assign Movie_ID as the primary key in the MOVIE relation? If no, then suggest an
appropriate primary key.
b) Is it correct to assign AudiNo as the primary key in the AUDI relation? If no, then suggest
appropriate primary key.
c) Is there any foreign key in any of these relations?
Answer:
a) Yes, because every movie will have it's unique id.
b) Yes, because every auditorium will be assigned a unique id. No two auditoriums will have same id.
c) Yes, Movie_ID in Audi table is the foreign because it references the Movie_ID in the Movie table.

7. An organisation wants to create a database EMPDEPENDENT to maintain following details about its
employees and their dependent.
EMPLOYEE(AadharNumber, Name, Address,Department,EmployeeID)
DEPENDENT(EmployeeID, DependentName, Relationship)
a) Name the attributes of EMPLOYEE, which can be used as candidate keys.
b) The company wants to retrieve details of dependent of a particular employee. Name the tables and
the key which are required to retrieve this detail
c) What is the degree of EMPLOYEE and DEPENDENT relation?
Answer:
a) AadharNumber and EmployeeID can be used for candidate keys because they are unique to every
employee.
b) Employee and Dependent tables are required. EmployeeID is the key to retrieve the required data.
c) Degree of Employee relation = 5 and degree of Dependent relation = 3 The number of attributes in a
relation is called the Degree of the relation
8. Suppose your school management has decided to conduct cricket matches between students of class
XI and Class XII. Students of each class are asked to join any one of the four teams — Team Titan,
Team Rockers, Team Magnet and Team Hurricane. During summer vacations, various matches will be
conducted between these teams. Help your sports teacher to do the following:

a) Create a database “Sports”.


b) Create a table “TEAM” with following considerations:
i) It should have a column TeamID for storing an integer value between 1 to 9, which refers to unique
identification of a team.
ii) Each TeamID should have its associated name (TeamName), which should be a string of length not
less than 10 characters
c. Using table level constraint, make TeamID as primary key
d. Show the structure of the table TEAM using SQL command.
Answer:
a.Create database Sports;
use Sports
b. create table team (teamidint(1), teamname varchar(10));
c. alter table team add primary key (teamid);
d. desc team;

SQL Operators
1. Mathematical Operators: SQL supports common mathematical operators such as + (addition), - (subtraction), *
(multiplication), and / (division). These operators are used for performing calculations on numeric data within the
database.

2. Relational Operators: - Relational operators like = (equal), <> (not equal), > (greater than), < (less than), >=
(greater than or equal to), and <= (less than or equal to) are used for comparing data values in SQL. They are crucial
for constructing conditional statements.

3.Logical Operators: - Logical operators such as AND, OR, and NOT are used to combine conditions in SQL queries.
They help in building complex query criteria and filtering data based on multiple conditions.

4. Aliasing and the DISTINCT Clause: - Aliasing allows you to provide temporary names for columns or tables in your
query results. It makes the output more readable and can be used to rename columns and tables.
- The DISTINCT clause is used to eliminate duplicate rows from the query result, ensuring that only unique rows are
displayed.

5. WHERE clause:- is essential for filtering and selecting specific rows that meet certain conditions. It supports
various operators to construct conditions, including:
- IN: Matches any of a list of values.
- BETWEEN: Selects values within a specific range.
- LIKE: Performs pattern matching with wildcard characters.
- IS NULL: Identifies rows with NULL values.
- IS NOT NULL: Identifies rows with non-NULL values.

6. ORDER BY: - The ORDER BY clause is used to sort the query result in ascending (ASC) or descending (DESC) order
based on one or more columns.
- It helps in organizing data for a more meaningful presentation.

7. Aggregate Functions: In the realm of databases, aggregate functions are essential tools for data summarization
and analysis.
MAX : Computes the maximum value within a given column.
MIN: Calculates the minimum value within a specified column.
AVG: Computes the average of values in a column.
SUM: Adds up all the values in a column.
COUNT: Counts the number of rows in a column or the number of non-null values.

8. GROUP BY and HAVING Clause for Data Summarization


- The GROUP BY clause allows you to group rows with identical values into summary rows.
- It is commonly used with aggregate functions to perform calculations on groups of data.
- The HAVING clause filters grouped results based on specified conditions, similar to the WHERE clause for individual
rows.

Where clause with Operators:

Relational operators: <, >, <=,>=, = ,!=( <>)


Select * from Empdata where salary > 20000;
Select * from Empdata where salary < 20000;
Select * from Empdata where salary >= 20000;
Select * from Empdata where salary <= 20000;
Select * from Empdata where Job=”Clerk”;
Select * from Empdata where Bonus=120;
Select * from Empdata where Address =”Mumbai”;
Select * from Empdata where Address != “Mumbai”;
Select * from Empdata where Job !=”Clerk”;
Select * from Empdata where Job <> ”Clerk”;
Logical Operator: and &&, or | , not !
Select * from Empdata where Job =”Clerk” and Address=”Noida”;
Select * from Empdata where Job =”Clerk” && Address=”Noida”;
Select * from Empdata where Job =”Clerk” or Bonus>100;
Select * from Empdata where Job =”Clerk” || Bonus>100;
Select * from Empdata where Job =”Clerk” and Address=”Noida” or Bonus>100;
Select * from Empdata where Job !=”Clerk”
Select * from Empdata where Job <> ”Clerk”
Select * from Empdata where not Job =”Clerk”

Distinct
MysQl DISTINCT is used to remove duplicate records from the table and fetch only the unique records.
The DISTINCT is only used with the SELECT statement.
Syntax: Select DISTINCT expression FROM tables WHERE condition;

Select DISTINCT job from Empdata;

Select distinct Address from Empdata;

Select Address from Empdata WHERE job=”Clerk”;

Select distinct Address from Empdata WHERE job=”Clerk”;

Between , Not Between


• The BETWEEN operator selects values within a given range.
• The values can be numbers, text or dates.
• The between operator is inclusive: begin and end values are included

Select * from Empdata where salary between 10000 and 20000;

Select * from Empdata where Doj between “2001-07-10” and “2003-12-10”;

Select * from Empdata where Doj >= “2001-07-10” and Doj <= “2003-12-10”;

Select * from Empdata where empid BETWEEN 101 and 107;

Select * from Empdata where empid NOT BETWEEN 101 and 107;

Select * from Empdata where Doj NOT BETWEEN “2001-07-10” and “2003-12-10”;

LIKE and NOT LIKE

Select * from Empdata WHERE address like “%a”;

Select * from Empdata WHERE address like “%a%”;


Select * from Empdata WHERE address like “%m%”;

Select * from Empdata WHERE address like “m%”;

Select * from Empdata WHERE address like “%i”;

Select * from Empdata WHERE address like “A%r”;

Select * from Empdata WHERE name like “F%”;

Select * from Empdata WHERE name like “%a”;

Select * from Empdata WHERE name like “%a%”;

Select * from Empdata WHERE doj like “2001-%-%”;

Select * from Empdata WHERE doj like “2001-07-%”;

Select * from Empdata WHERE doj like “%-%-10”;

Select * from Empdata WHERE name like “_a%”;

Select * from Empdata WHERE name like “%s_”;

Select * from Empdata WHERE name like “__a%”;

Select * from Empdata WHERE name like “_____”;

Select * from Empdata WHERE doj like “___1-%-10”;

Select * from Empdata WHERE address like “%b__”;

IS NULL, IS NOT NULL


Select * from Empdata WHERE address IS NULL;
Select * from Empdata WHERE doj IS NULL;

Update Empdata SET Address=”Kolkata” where Address IS NULL;

Select * from Empdata WHERE doj IS NOT NULL;


Multiple Choice Questions
1. Which keyword is used to sort the records of a table in descending order ? Answer : DESC
2. Which clause is used to sort the records of a table ? Answer : ORDER BY
3. Which command is used to modify the records of the table ? Answer : UPDATE
4. Which clause is used to remove the duplicating rows of the table? Answer : DISTINCT
5. What is the use of IS NULL operator ? Answer : It checks whether the column has null value / no value.
6. Which of the following statement is not true for the update command?
a. In the absence of WHERE clause, it updates all the records of the table.
b. Using WHERE clause with Update, only one record can be changed.
c. With WHERE clause of the UPDATE statements, multiple records can be changed.
d. None of these.
7. All aggregate functions ignore NULLs except for ________ function.
a. Distinct b.Count(*) c. Average() d. None of these.
8. For the HAVING clause, which of the following phrases is/are true?
a. Acts EXACTLY like a WHERE clause.
b. Acts like a WHERE clause but is used for the columns rather than groups
c. Acts like a WHERE clause but is used for groups rather than rows.
d. Acts like a WHERE clause but is used for rows rather than columns.
9. Aggregate functions can be used in the select list or the _______ clause of a select statement. They
cannot be used in a _________ clause.
a. Where, having b. Group by, having.
c. Having, where d.Group, where
10. Only ______________ functions are used with the GROUP BY clause.
a. Text b. Math c. Date/ Time d. Aggregate
11. Raj, a Database Administrator, needs to display the average pay of workers from those departments
which have more than five employees. He is experiencing a problem while running the following
query:
SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT (*) > 5 GROUP BY DEPT;
Which of the following is a correct query to perform the given task?
a. SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT (*) > 5 GROUP BY DEPT;
b. SELECT DEPT, AVG(SAL) FROM EMP HAVING COUNT (*) > 5 GROUP BY DEPT;
c. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT WHERE COUNT (*) > 5;
d. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING COUNT (*) > 5;
12. Which of the following aggregation operation adds up all the values of the attribute?
a. ADD () b. AVG () c. MAX () d. SUM ()
13. In MySQL, identify the correct query used in ordering the values of a field namely marks in the table
STUDENT in ascending order:
i) Select * From Student Order by marks asc; ii) Select * From Student Order by marks desc;
iii) Select * From Student Order by marks; iv) Both (i) and (iii)
14. If column “salary” contains the data set (45000, 5000, 55000, 45000, 55000), what will be the output
after the execution of the given query?
SELECT AVG (DISTINCT salary) FROM employee;
(i) 38500 (ii) 40000 (iii) 41000 (iv) 35000
15. The correct SQL from below to display the city and temperature in increasing order of the
temperature.
(i) SELECT city FROM weather order by temperature ;
(ii) SELECT city, temperature FROM weather ;
(iii) SELECT city, temperature FROM weather ORDER BY temperature ;
SELECT city, temperature FROM weather ORDER BY city ;
16. In column “Margin “contains the data set(2.00,2.00,NULL,4.00,NULL,3.00,3.00). What will be the
output of after the execution of the given query?
SELECT AVG(Margin) FROM SHOP;
A. 2.9 B. 2.8 C. 2.00 D. All of these
17. If column “salary” of table “EMP” contains the dataset {10000, 15000, 25000,10000, 25000}, what will
be the output of following SQL statement?
SELECT SUM(DISTINCT SALARY) FROM EMP;
A. 75000 B. 25000 C. 10000 D. 50000
18. Which SQL statement is used to display all the data from product table in the decreasing order of
price?
A. SELECT * FROM PRODUCT;
B. SELECT * FROM PRODUCT ORDER BY PRICE;
C. SELECT * FROM PRODUCT ORDER BY PRICE DESC;
D. SELECT * FROM PRODUCT ORDER BY DESC;

ASSERTION ( A ) and REASONING ( R ) based questions.


a. Both A and R are true and R is the correct explanation for A
b. Both A and R are true and R is not the correct explanation for A
c. A is True but R is False
d. A is false but R is True
1. Assertion ( A ) : ORDER BY Clause is used to sort the records.
Reason ( R ) : For sorting, the keywords ASC and DESC are used.
Answer: Both A and R are true and R is the correct explanation for A.
2. Assertion ( A ) : The UNIQUE keyword ensures no duplicate value in table.
Reason ( R ) : DISTINCT is similar to UNIQUE.
Answer: Both A and R are true and R is the correct explanation for A.
3. Assertion (A): The ORDER BY clause sorts the result set in descending order by default.
Reason (R): To sort a result set in ascending order we can use ASC keyword with ORDER BY clause. (D)

4. Assertion (A): HAVING clause is often used with the GROUP BY statement.
Reason (R): HAVING clause is used to check specified condition. (A)

5. Assertion (A):- Order by clause sorts fields in a table in ascending or descending order.
Reasoning (R): - The WHERE clause is placed before the ORDER BY clause. (b)

SHORT ANSWER QUESTIONS


1. Categorize the following commands into DDL and DML commands ?
INSERT INTO , DROP TABLE, ALTER TABLE, UPDATE … SET, SELECT, DELETE
Answer : DDL commands : DROP TABLE, ALTER TABLE,
DML commands: INSERT INTO, UPDATE … SET, SELECT, DELETE
2. You have a database table named "Employees" with columns "EmployeeID," "FirstName," and
"LastName." Write an SQL query to retrieve the first and last names of all employees whose first
name is "John."
Answer : SELECT FirstName, LastName FROM Employees WHERE FirstName = 'John';
3. You have a table named "Products" with columns "ProductID," "ProductName," and "Price."
Write an SQL query to update the price of a product with a ProductID of 101 to $25.50
Answer : UPDATE Products SET Price = 25.50 WHERE ProductID = 101;
4. There is table named SALES, which have the attributes PROD_ID, P_NAME, QTY. (PROD_ID
date-type is CHAR (5), P_NAME data-type is char(20) ,QTY is NUM)
Write SQL statements for the following :
(a) Insert a row with data (A101, SHAMPOO, 200 )
(b) Delete the record whose PROD_ID is A101
Answer : a) INSERT INTO SALES VALUES(‘A101’, ‘SHAMPOO’ ,200 )
b) DELETE FROM SALES WHERE PROD_ID = ‘A101’ ;
5. There is table named EMP, which have the attributes EMP_ID, E_NAME, SALARY . (EMP_ID
date-type is CHAR (5), E_NAME data-type is char(20) , SALARY is NUM)
Write SQL statements for the following :
a)Display the records of those employees whose salary is greater than 25000.
b)Arrange the records in the decreasing order of their salary.
Answer : a) SELECT * FROM EMP WHERE SALARY>25000 ;
b) SELECT * FROM EMP ORDER BY SALARY DESC ;
6. Write SQL Queries for (a) , (b) and (c) , which are based on the table
STUDENT(AdmNo,Name,Class,DOB,City)
a. Display the records from the table STUDENT in Alphabetical order as per the name of the
students. b. Display Name, Class, DOB and City whose marks is between 40 & 551. c. Display
the list of City but duplicate values should not be there.
Answer : a.SELECT * FROM STUDENT ORDER BY NAME ;
b.SELECT NAME, CLASS, DOB, CITY FROM STUDENT where marks between 40 and 551.
c.SELECT DISTINCT CITY FROM STUDENT ;
7. TID TName TSal TDept TDesig
1 Amit 2000 IT PGT
2 Sunit 1500 HISTORY TGT
3 Naina 1800 MATH PGT
Write the sql command for the following queries and answer the question
a. What is degree and Cardinality of the Table : Teacher
b. Identify the primary key in the table
c. Display the records of all PGT staff
d. Increase the salary of teachers of Math Department BY 20%.
Answer :
a. Degree 5, Cardinality 3
b.TID
c. Select * from Teacher Where TDesig =PGT;
d. Update Teacher set salary= salary + salay *20/100 Where TDept=”Math”;
8. Consider the table GAMES given below:

Write SQL commands for the following:


(i) To display details of those games which are having Prize Money more than 7000;
(ii) To display sum of Prize Money for each type of GAME.
(iii) To display the total number of games available in the above table GAMES.
Answer:
i) SELECT * FROM GAMES WHERE Prize_Money> 7000;
ii) SELECT SUM (Prize_Money), Type FROM GAMES GROUP BY Type;
iii) SELECT COUNT (Games_Name) FROM GAMES;
9. Satyam. a database analyst has created thefollowing table:

He has written following queries:


(i) select sum (Marks) from student where Optional= 'IP' and STREAM= 'Commerce';
(ii) select max (Marks) + min (Marks) from student where Optional = ‘CS';
(iii) select avg (Marks) from student where Optional = 'IP';
(iv) select length (SName) from student where Marks is NULL;
Help him in predicting the output of the above given queries
Answer: i. 193 ii. 194 iii. 93.75 iv. 6
10. Carefully observe the following table named ‘stock’:

Write SQL queries for the following:


(A) To display the records in decreasing order of price.
(B) To display category and category wise total quantities of products.
(C) To display the category and its average price.
(D)To display category and category wise highest price of the product
Answer:
(A)select * from stock order by price desc;
(B)select category, sum(qty) from stock group bycategory;
(C)select category, avg(price) from stock group bycategory;
(D)select category, max(price) from stock group by category;
11. Kabir has created following table named exam:

Help him in writing SQL queries to the perform the following task:
i. Insert a new record in the table having following values: [6,'Khushi','CS',85]
ii. To change the value “IP” to “Informatics Practices” in subject column.
iii. To remove the records of those students whose marks are less than 30.
iv. To add a new column Grade of suitable datatype.
v. To display records of “Informatics Practices” subject.
Answer:
i. INSERT INTO EXAM VALUES(6,'Khushi','CS',85);
ii. UPDATE EXAM SET subject= "Informatics Practices" where subject = "IP";
iii. DELETE FROM EXAM WHERE marks < 30;
iv. ALTER TABLE EXAM ADD COLUMN grade varchar (2);
v. Select * from exam where subject="Informatics Practices";
12. Consider the following table 'Furniture'. Write SQL commands for the statements (i)to (iii) and write
output for SQL queries (iv) and (v).

(i) To display FCODE and NAME of each Furniture Item in descending order of FCODE.
(ii) To display the average PRICE of all the Furniture Items, which are made of Wood with
WCODE as W02.
(iii) To display WCODE wise, WCODE and the highest price of Furniture Items.
(iv) SELECT SUM (PRICE) FROM Furniture WHERE WCODE = ‘W03’;
(v) SELECT COUNT (DISTINCT PRICE) FROM Furniture;
Answer:
(i) SELECT FCODE, NAME FROM FurnitureORDER BY FCODE DESC;
(ii) SELECT AVG (PRICE) FROM Furniture WHERE WCODE = ‘W02’;
(iii) SELECT WCODE, MAX(PRICE) FROM Furniture GROUP BY WCODE;

13. Consider the following table Activity. Write SQL Commands for the statements (i) to (ii) and output for
SQLqueries (iii) to (v).
(i) To display names of Participants and pointsin descending order of points.
(ii) To display House wise total points scored along with House name. (i.e. display the HOUSE
and total pointsscored by each HOUSE.)
(iii) SELECT AVERAGE (POINTS) FROM Activity WHERE HOUSE = 'Gandhi' orHOUSE = 'Bose':
(iv) SELECT COUNT (DISTINCT POINTS) FROM ACTIVITY;
(v) SELECT SUM(POINTS) FROM ACTIVITY;
Answer:
i. SELECT PARTICIPANTPOINTS FROM Activity ORDER BY POINTS DESC;
ii. SELECT HOUSE, SUM(POINTS) FROM Activity GROUP BY HOUSE;
iii. 250
iv. 4
1500
14. Naveen, a database administrator has designed a database for a Computer Stock.
Help her by writing answers of the following questions based on the given table:
TABLE: Stock

A. Write a query to display product name in upper case.


B. To display the records in descending order of the price.
C. To display category and category wise highest price of product.
OR (Option for part C only)
To display category and category wise total quantities of product
Answer:
A. SELECT UPPER(PNAME) FROM STOCK;
B. SELECT* FEOM STOCK ORDER BY PRICE DESC;
C. SELECT CATEGORY,MAX(PRICE) FROM STOCK GROUP BY CATEGORY;
OR
SELECT CATEGORY,SUM(QTY) FROM STOCK GROUP BY CATEGORY;
Interface of python with an SQL database
In order to connect to a database from within Python, you need a library(mysql connector) that provides
connectivity functionality. Steps for Creating Database Connectivity Applications There are mainly seven steps that
must be followed in order to create a database connectivity application.
Step 1: Start Python.
Step 2: Import the packages required for database programming.
Step 3: Open a connection to database.
Step 4: Create a cursor instance.
Step 5: Execute a query.
Step 6: Extract data from result set.
Step 7: Clean up the environment.

CODE FOR CREATING A MYSQL DATABASE THROUGH PYTHON:


import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="mohana", password="mohana")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

CODE FOR CREATING A TABLE IN MYSQL THROUGH PYTHON


import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="mohana",password="mohana", database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

CODE FOR INSERTING DATA IN A MYSQL TABLE THROUGH PYTHON


import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="mohana",password="mohana", database="mydatabase")
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Tom", "ABCD")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

CODE FOR SELECTING AND PRINTING DATA FROM A MYSQL TABLE THROUGH PYTHON
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="mohana",password="mohana", database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
CODE FOR DELETING A RECORD FROM MYSQL TABLE USING PYTHON
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="mohana",password="mohana", database="mydatabase")
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE name = 'XYZ'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")

CODE FOR UPDATING A RECORD FROM MYSQL TABLE USING PYTHON


import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="mohana",password="mohana", database="mydatabase")
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

IMPORTANT CONNECTIVITY METHODS :


1. Connectivity Basics: Important functions and its purpose :
- connect( ): Establishes a connection to the database.
- cursor( ): Creates a cursor object to execute SQL queries.
- execute( ): Executes SQL commands.
- commit( ): Saves changes made during the transaction.
2. Fetching Data:
- fetchone( ): Retrieves the next row of a query result set.
- fetchall( ): Fetches all rows of a query result set.
- rowcount: Returns the number of rows affected by the last executed command.
3. Creating Database Applications:
Developing applications involves connecting to the database, executing queries, and processing results. Utilize
`connect()`, `cursor()`, and `execute()` for database operations.
4. Query Formatting:
- ‘%s` Format Specifier or format( ) : Used to dynamically insert values into SQL queries.
- Enhances query flexibility and security by preventing SQL injection attacks.

MCQs
1. Looking at the code below, what would this line do?
INSERT INTO Cats (name, breed) VALUES ('Petunia', 'American Shorthair')
A. Add a table to the Cats database with the name "Petunia" and breed "American Shorthair".
B. Add a row to the Cats table with the name "Petunia" and the breed "American Shorthair".
C. Create the table Cats.
D. Add a row to the Cats table with the name "American Shorthair" and the breed "Petunia".

2. Looking at the code below, what would this line do to the table Cats?
cur.execute('DROP TABLE IF EXISTS Cats ')
A. It will remove the row "Cats". B. It will move "Cats" to the end of the database.
C. It will remove the column "Cats". D. It will remove the table "Cats".
3. True or False? A cursor is used to create a database. A. True B. False
4. CONNECT() function in SQL is used for:
A. To connect to database. B. To open database
C. To create database D. All of the above
5. which method is used to retrieve N number of records
A. fetchone() B. fetchall() C. fetchmany() D. fetchN()

6. Which of the following is not the function of the MYSQL in python ?


A. .connect() B. .close() C. .execute() D. .raw()
7. Which keyword we use to fetch the data from the table in database ?
A. fetch B. select C. raw D. All of the above

8. In python, connect() returns _________.


A. Connection object. B. Database object C. Database name D. Connector class
9. What does the `fetchone()` function do in database connectivity?
A. Fetches the first row of the query result B. Fetches all rows of the query result
C. Fetches a specific row based on the index D. Fetches the last row of the query result

10. How is dynamic insertion of values achieved in SQL queries?


A. Using `execute()` B. Using `%s` format specifier or `format()`
C. Using `dynamicValues()` D. Using `insertValues()`

SHORT ANSWER QUESTIONS

1. A STUDENT HAS WRITTEN THE FOLLOWING CODE


Explain what the following query will do?
import mysql.connector
db = mysql.connector.connect(….)
cursor = db.cursor()
person_id = input("Enter required person id")
lastname = input("Enter required lastname")
db.execute("INSERT INTO staff (person_id, lastname) VALUES ({}, ‘{}’) ". format (person_id, lastname))
db.commit()
db.close()
ANS. This above program insert a new records in table staff such that person_id and lastname are input by
user..

2. ABC Infotech Pvt. Ltd. needs to store, retrieve and delete the records of its employees. Develop an interface
that provides front-end interaction through Python, and stores and updates records using MySQL.
The operations on MySQL table "emp" involve reading, searching, updating and deleting the records of
employees.
Program to read and fetch all the records from EMP table having salary more than 70000.
Answer :-
import mysql.connector db1 = mysql.connector.connect (host = "localhost", user = "root", password =
"pathwalla", database = "company")
cursor = db1.cursor()
sql = "SELECT FROM EMP WHERE SALARY> 70000;"
try:
cursor.execute(sql)
resultset = cursor.fetchall ()
for row in resultset:
empno = row [0]
ename = row [1]
salary = row [2]
print (("empno-3d, ename=%s, salary-8f") % (empno, ename, salary))
except:
print ("Error: unable to fetch data")
db1.close()
3. import ______ mysql.connector______________ # line 1
mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword",
database="mydatabase" )
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
______ mydb.commit()___________ # line 2

4. The given program is used to connect python with MySQL and show all the data present in the table
“stmaster” from the database “oraclenk”. You are required to complete the statements so that the code can
be executed properly.
import _____.connector __ pymysql #STATEMENT1
dbcon=pymysql._____________(host=”localhost”,user=”root”,________=”sia@1928”) #STATEMENT2
if dbcon.isconnected()==False
print(“Error in establishing connection:”)
cur=dbcon.______________() #STATEMENT3
query=”select * from stmaster”
cur.execute(_________)#STATEMENT4
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.______() #STATEMENT5

Answer:
1 mysql, as 2 connect, passwd 3 cursor 4 query 5 close

You might also like