XII-Comp. Sc.
XII-Comp. Sc.
XII-Comp. Sc.
Deputy Commissioner
KVS , Regional Office , Kolkata
Guiding Force
Mr. Sanjib Sinha , Assistant Commissioner, KVS Kolkata Region
Coordinated By
Mrs. Sabiha Shahin , Principal , KV No. 2 Kanchrapara
Resource Persons
Mr. Kamal Kant Gupta, PGT (Comp. Sc.) , KV Tarkeshwar
&
Mr. Aftab Alam Shahnawaz , PGT(Comp. Sc.) , KV No. 2 Kanchrapara
2
CONTENTS :
Unit Title Page #
3
UNIT -1 : PYTHON REVISION TOUR
1. Introduction to Python:
- Python Language: High-level, interpreted programming language known for its simplicity
and readability.
- Usage: Widely used in web development, data analysis, artificial intelligence, scientific
computing, and more.
- Easy to Learn: Simple and clean syntax makes it beginner-friendly.
- Interpreted Language: Code is executed line by line, aiding in debugging.
3. Operators:
- Arithmetic Operators: Perform basic math operations (+, -, *, /, %).
- Comparison Operators: Compare values (==, !=, <, >, <=, >=).
- Logical Operators: Combine conditions (and, or, not).
4. Control Structures:
- Conditional Statements: Make decisions in code ( if, elif, else).
- Example:
if condition:
# Code block executed if condition is true
elif another_condition:
# Executed if the first condition is false and this condition is true
else:
# Executed if no condition is true
- Loops: Repeat code blocks (for, while).
4
- Example (for loop):
for item in list:
# Code block executed for each item in the list
- Loop Control Statements: Modify loop behavior (break, continue).
3. To store terms in terms of keys and values, what core data type does python provide
?
(a)list (b)tuple (c) class (d) dictionary
Ans. – (d)
Ans. – (a)
5. List AL is defined as follows : AL = [1,2,3,4,5]
Which of the following statement remove the middle element 3 from it so that the list
AL equals [1,2,4,5]
(a) del a[2] (b) a[2:3] = [ ] (c) a[2:2] = [ ] (d) a[2] = [ ] (e) a.remove(3)
Ans. – (a, b, e)
6
(c) Day = [1: ‘Monday’, 2: ‘Tuesday’, 3: ‘Wednesday’]
(d) Day = {1 ‘Monday’, 2 ‘Tuesday’, 3 ‘Wednesday’ }
Ans. – (a)
True/False Questions:
1. A dictionary can contain keys of any valid Python types.
2. For any index n, s[:n] + s[n:] will give you original string s.
3. A list of character is similar to a string type.
4. The max() and min() when used with tuples can work if elements of the tuple
are all of the same type.
7
return n[0], n[1], n[2], n[3]
L=[23,35,47]
m1, m2, m3, m4 = increment (L)
print(L)
print (m1, m2, m3, m4)
print (L[3] == m4)
Q3. Find and write the output of the following python code :
x = “klmnopqrst”
i= “k”
while i in x :
print ( i, end = “ “)
Q4. Predict the output of the following code fragment:
Values = [ ]
for i in range (1,4):
values. append(i)
print (values)
Q5. What will be the output of the following code snippet ?
dc1 = { }
dc[1] = 1
dc[‘1’] = 2
dc1[1.0] = 4
sum = 0
for k in dc1 :
sum + = dc1[k]
print (sum)
Q6. Predict the output of the Python code given below:
tuple1 = (11, 22, 33, 44, 55 ,66)
list1 =list(tuple1)
new_list = [ ]
for i in list1:
if i%2==0:
8
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
Short Answer Questions (Consisting 03 Marks each ) :
Q1. What is the output of following code fragments ?
[3]
def increment(n):
n.append([49])
return n[0],n[1],n[2],n[3]
L= [1,2,3]
m1, m2, m3, m4 = increment (L)
print(L)
print(m1, m2, m3, m4)
print(L[3] == m4)
Q2. Find the output of the following python program :
country = { }
f1 = [ ‘India’, ‘Russia’, ‘india’, ‘Russia’]
for index in f1:
if index in country:
country[index] +=1
else :
country[index]=1
print(country)
print( len (country))
Q3. Write a python program using function NOVOWEL (N) which accepts a list of strings as
arguments N and appends all words of the strings which have no vowels in it, into a new list
named NV. The main program will receive the list of words from user, and send the list through
calling function NOVOWEL().
For Example:
Suppose the list of string accepted by N are :
9
[‘DRY’, ‘LIKE’, ‘RHYTHM’, ‘WORK’, ‘GYM’]
Then the new list NV should store:
[‘DRY’, ‘RHYTHM’, ‘GYM’]
10
Q9. Following code is trying to create a tuple with a single item. But when we try to obtain the
length of the tuple is, Python gives error. Why ? What is solution?
>>> t=(6)
>>> len(t)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
len(t)
TypeError: object of type 'int' has no len()
Q10. How are dictionaries different from list?
CASE STUDY BASED QUESTION:
Q. Predict the output of the code given below:
s="welcome2cs"
n = len(s)
m="" for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&' print(m)
11
UNIT -2 : EXCEPTION HANDLING
- `try`: This block contains the code that might raise an exception.
- `except ExceptionType`: If an exception of the specified type occurs in the "try" block, the
code within the "except" block will execute to handle the exception.
Example 1: Handling Division by Zero
try:
numerator = 10
denominator = 0
result = numerator / denominator # This may raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero.")
try:
# Code that may raise exceptions
except ExceptionType:
# Handle the exception
finally:
# Code that always executes
Example: Using `finally`
try:
file = open("sample.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close() # Close the file, even if an exception occurred or not.
Multiple Choice Questions (MCQ)
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
Answer: C
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
13
- C. To indicate the end of the try-except construct
- D. To prevent exceptions from occurring
Answer: A
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
Answer: B
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
Answer: B
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`
Answer: C
6. In a try-except block with multiple except blocks, which block will be executed if an
exception matches multiple except blocks?
- A. The first matching except block encountered from top to bottom
- B. All matching except blocks simultaneously
- C. The last matching except block encountered from top to bottom
- D. None of the above
Answer: A
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
Answer: C
8. Which exception is raised when attempting to access a non-existent file?
- A. FileNotFoundError - B. FileNotAccessibleError
- C. NonExistentFileError - D. InvalidFileAccessError
Answer: A
14
9. 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
Answer: C
10. 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
Answer: A
15
Answer: A
15. Assertion: The `finally` block is used to prevent exceptions from occurring.
Reason: The `finally` block ensures that no exceptions can be raised in the associated code.
Answer: B
True/False Questions
16. True or False: The primary purpose of exception handling is to prevent any errors from
occurring in a program. (False)
17. True or False: The `finally` block is optional in a try-except construct. (True)
18. True or False: You can handle multiple exceptions using a single `except` block. (False)
19. True or False: The `finally` block is commonly used to perform cleanup operations.(True
20. True or False: The `finally` block can be omitted in a try-except-finally construct.(True)
16
Answer: Multiple `except` blocks are appropriate when different types of exceptions can
occur within the same `try` block, and you want to handle them differently. For instance, you
might handle a `ValueError` differently from a `TypeError`.
Answer:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("Error: File not found.")
27. Explain the purpose of using multiple `except` blocks within a single `try` block.
Answer: Multiple `except` blocks are used to handle different types of exceptions that may
occur within the same `try` block. This allows you to provide specific error-handling code for
each type of exception.
28. Describe the sequence of execution in a `try-except-finally` block when an exception
occurs in the `try` block.
Answer: When an exception occurs in the `try` block of a `try-except-finally` construct, the
program jumps to the corresponding `except` block (if matching) to handle the exception.
After the `except` block executes (or if there's no exception), the `finally` block is executed.
29. 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.
17
30. Explain the key benefit of using exception handling in programming and provide an
example of when it can be particularly useful.
Answer:The key benefit of using exception handling is to gracefully manage errors,
preventing program crashes and improving code reliability. For example, when reading user
input, exception handling can prevent the program from crashing due to invalid input,
allowing it to recover and prompt the user for valid input instead.
Case-Based Questions
Case 1:
You are developing a banking application where users can withdraw money from their
accounts. Implement a try-except block to handle the scenario when a user tries to withdraw
more money than their account balance. Provide the code for the try-except block and explain
how it works.
Answer:
try:
withdrawal_amount = float(input("Enter withdrawal amount: "))
account_balance = 1000.0 # Assume initial balance
if withdrawal_amount > account_balance:
raise ValueError("Insufficient balance")
else:
account_balance -= withdrawal_amount
print(f"Withdrawal successful. New balance: {account_balance}")
except ValueError as e:
print(f"Error: {e}")
In this case, the try-except block attempts to withdraw money from the account. If the
withdrawal amount exceeds the account balance, a `ValueError` exception is raised with the
message "Insufficient balance," which is caught and handled by the except block.
Case 2:
You are writing code to read data from a user-provided file. Implement a try-except-finally
block to handle the following scenarios: opening the file, reading its contents, and closing the
file. Provide the code and explain how it ensures proper resource management.
18
Answer:
try:
file = open("user_file.txt", "r") # Try to open the file
data = file.read() # Try to read the file contents
except FileNotFoundError:
print("Error: File not found.")
except IOError:
print("Error: Could not read the file.")
finally:
try:
file.close() # Attempt to close the file, even if an exception occurred
except NameError:
pass # Handle the case where 'file' was never opened
# Continue processing data if the file was successfully opened and read
if "data" in locals():
print("Data read successfully:")
print(data)
In this case, the try-except-finally block attempts to open the file, read its contents, and close
the file. The `finally` block ensures that the file is closed properly, even if an exception
occurred during opening or reading. If the file was successfully opened and read, the data is
processed further.
Introduction to Functions
A function is a block of organized, reusable code that performs a specific task. In Python,
functions are essential for modularity and code reusability. In this study material, we will
cover various aspects of functions, including types of functions, creating user-defined
functions, handling arguments and parameters, default parameters, positional parameters,
functions returning values, the flow of execution, and the scope of variables.
Types of Functions
1. Built-in Functions
19
Built-in functions are pre-defined functions provided by Python. These
functions are readily available for use without the need for additional coding.
Examples include print( ) , len( ) , max( ) , and abs( ).
3. User-Defined Functions
User-defined functions are functions created by the programmer to perform
specific tasks. These functions enhance code reusability and readability.
You can define your own functions using the `def` keyword.
Default Parameters
You can provide default values for parameters in a function. If an argument is not
provided when calling the function, it will use the default value specified in the
function definition.
#Code example :
def greet(name="Guest"):
print(f"Hello, {name}!")
Positional Parameters
20
Positional parameters are matched to arguments based on their position. The order in
which you pass arguments matters. For example, in `my_function(a, b)`, `a`
corresponds to the first argument, and `b` corresponds to the second.
# Code example :
def add(a, b):
return a + b
Flow of Execution
When a program calls a function, it transfers control to the function. After the function
completes its task or reaches a `return` statement, control returns to the calling code.
Scope of a Variable
Global Scope
Variables defined outside of any function have global scope. They can be accessed
from any part of the code, both inside and outside functions. To access a global
variable in a local scope we use the keyword ‘global’
Local Scope
Variables defined inside a function have local scope. They are only accessible within
that function. Local variables are created when the function is called and destroyed
when it exits.
- Example:
global_var = 10 # Global variable
def some_function():
local_var = 5 # Local variable
global var
global_var = 25 # accessing the global variable var and assigning it with
# value 25
21
C. Module function D. None of the above
Answer: A
22
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.
Answer: C
9. What is the scope of a variable defined outside of any function?
A. Global scope B. Local scope
C. Module scope D. Function scope
Answer: A
10. Variables defined inside a function have which scope?
A. Global scope B. Local scope
C. Module scope D. Function scope
Answer: B
23
Reason: User-defined functions are created using the `print` keyword.
Answer: D
15. 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.
Answer: B
True/False Questions
16. True or False: Python's built-in functions are predefined and don't require additional
coding. (True)
17. True or False: User-defined functions cannot have default parameters. (False)
18. True or False: Positional parameters in a function are matched to arguments based on their
names. (False)
19. True or False: Local variables defined inside a function have global scope.(False)
20. True or False: A function can return multiple values in Python. (True)
24
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.
Short Answer Questions (SA-2)
26. 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
This function calculates the factorial of a number `n` by repeatedly multiplying `n` with the
previous iteration value of n in the loop
27. 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.
28. Describe the process of variable shadowing in Python and provide an example.
Answer:Variable shadowing occurs when a local variable in a function has the same name as
a global variable, causing the local variable to "shadow" the global one within that function's
scope. For example:
#code example
x = 10
def my_function():
x=5
print(x)
my_function() # Output: 5
print(x) # Output: 10
Inside `my_function`, the local `x` shadows the global `x`.
29. What is the purpose of using the `global` keyword in Python? Provide an example.
Answer:The `global` keyword is used to indicate that a variable inside a function should
refer to the global variable with the same name. Example:
#code example
25
x = 10
def modify_global():
global x
x += 5
modify_global()
print(x) # Output: 15
Case-Based Questions
Case 1:
You are working on a project where you need to calculate the average of test scores for a
class. You have decided to use a Python function to perform this task. Write a user-defined
function to calculate the average and explain how you would call this function to find the
average of five test scores.
Answer:
# Python code example
def calculate_average(test_scores):
total = sum(test_scores)
average = total / len(test_scores)
return average
In this case, we define the `calculate_average` function that takes a list of test scores as a
parameter, calculates the total, and then returns the average. We call this function with a list of
five test scores and print the result.
Case 2:
You are designing a program to manage a library. You want to keep track of the total number
of books available globally and within each library branch. Explain how you would use global
and local variables to achieve this.
26
Answer:
You can use global variables to keep track of the total number of books available globally
across all branches of the library. Additionally, you can use local variables within each
branch's functions to keep track of the number of books available at each branch. Here's an
example:
#Python code
total_books = 0 # Global variable to track total books across all branches
def add_books(branch, quantity):
global total_books # Access the global variable
total_books += quantity # Update the global count
branch_books = quantity # Local variable for the specific branch
return branch_books
# Example usage:
branch1_books = add_books("Branch 1", 50)
branch2_books = add_books("Branch 2", 30)
branch1_books_removed = remove_books("Branch 1", 10)
27
UNIT -4 : DATA FILE HANDLING
• We have seen yet only the transient programs. The programs which run for a short
period of time and give some output and after that their data is disappeared. And when
we again run those programs then we have to use new data.
• This is because the data is entered in primary memory which is temporary memory
and its data is volatile.
• Those programs which are persistent i.e. they are always in running or run for a long
time then their data is stored in permanent storage (e.g. harddisk) . If the program is
closed or restarted then the data used will be retrieved.
• For this purpose the program should have the capability to read or write the text files
or data files. These files can be saved in permanent storage.
• The meaning of File I/O (input-output) is to transfer the data from Primary memory
to secondary memory and vice-versa.
28
Basic File Types
Text File: A text file is sequence of line and line is the sequence of characters and this file is
saved in a permanent storage device. Although in python default character codingis ASCII
but by using constant ‘U’ this can be converted into UNICODE. In Text File each line
terminates with a special character which is EOL (End Of Line). These are in human readable
form and these can be created using any text editor.
Binary File: Binary files are used to store binary data suchas images, videos audio etc.
Generally numbers are stored in binary files. In binary file, there is no delimiter to end a line.
Since they are directly in the form of binary hence there is noneed to translate them. That’s
why these files are easy and fast in working.
Opening & Closing Files
➢ We need a file variable or file handle to work with files in Python.
➢ This file object can be created by using open( ) function or file( ) function.
➢ Open( ) function creates a file object, which is used later to access the file using the
functions related to file manipulation.
➢ Its syntax is following -
<file_object> = open(<file_name>,<access_mode>)
or
<file_object> = file(<file_name,<access_mode>)
rb+ To Read and write binary file. But the file pointer will be at the beginning ofthe file.
29
w Only writing mode, if file is existing the old file will be overwritten else the newfile will be
created.
wb Binary file only in writing mode, if file is existing the old file will be overwrittenelse the new
file will be created.
wb+ Binary file only in reading and writing mode, if file is existing the old file will be
overwritten else the new file will be created.
a Append mode. The file pointer will be at the end of the file.
ab Append mode in binary file. The file pointer will be at the end of the file.
a+ Appending and reading if the file is existing then file pointer will be at the endof the file else
new file will be created for reading and writing.
ab+ Appending and reading in binary file if the file is existing then file pointer willbe at the end of
the file else new file will be created for reading and writing.
30
with open("example.txt", "w") as file:
file.write("This is a line of text.\n")
31
for line in lines:
print(line)
Binary files are stored in terms of bytes (0s and 1s), but unlike text files, these bytes do not
represent the ASCII values of characters. Rather, they represent the actual content such as
image, audio, video, compressed versions of other files, executable files, etc. These files are
not human readable. Thus, trying to open a binary file using a text editor will show some
garbage values. We need specific software to read or write the contents of a binary file.
Binary files are stored in a computer in a sequence of bytes. Even a single bit change can
corrupt the file and make it unreadable to the supporting application. Also, it is difficult to
remove any error which may occur in the binary file as the stored contents are not human
readable. We can read and write both text and binary files through Python programs.
32
moved.
Example Code :
f = open("a.dat", 'wb')
line = ‘G20 Presidency\nOne Earth, One Family, One Future'
f.write(line)
f.close()
f = open("a.txt", 'rb+')
print(f.tell())
print(f.read(7)) # read seven characters
print(f.tell())
print(f.read())
print(f.tell())
f.seek(9,0) # moves to 9 position from beginning
print(f.read(5))
f.seek(4, 1) # moves to 4 position from current location
print(f.read(5))
f.seek(-5, 2) # Go to the 5th byte before the end
print(f.read(5))
f.close()
We know that Python considers everything as an object. So, all data types including list, tuple,
dictionary, etc. are also considered as objects. During execution of a program, we may require
to store current state of variables so that we can retrieve them later to its present
state. Suppose you are playing a video game, and after some time, you want to close it. So, the
program should be able to store the current state of the game, including current level/stage,
your score, etc. as a Python object. Likewise, you may like to store a Python dictionary as an
object, to be able to retrieve later. To save any object structure along with data, Python
provides a module called Pickle. The module Pickle is used for serializing
and de-serializing any Python object structure. Pickling is a method of preserving food items
by placing them in some solution, which increases the shelf life. In other words, it is a method
to store food items for later consumption.
The pickle module deals with binary files. Here, data are not written but dumped and
similarly, data are not read but loaded. The Pickle Module must be imported to load and dump
data. The pickle module provides two methods - dump() and load() to work with binary files
for pickling and unpickling, respectively.
33
This method is used to convert (pickling) Python objects for writing data in a binary file. The
file in which data are to be dumped, needs to be opened in binary write mode (wb).
where data_object is the object that has to be dumped to the file with the file handle named
file_object. For example, following Program writes the record of a student (roll_no, name,
gender and marks) in the binary file named mybinary.dat using the dump(). We need to close
the file after pickling.
This method is used to load (unpickling) data from a binary file. The file to be loaded is
opened in binary read (rb) mode. Syntax of load() is as follows:
Store_object = load(file_object)
Here, the pickled Python object is loaded from the file having a file handle named file_object
and is stored in a new file handle called store_object. The following program demonstrates
how to read data from the file mybinary.dat using the load().
Output of Program:
The data that were stored in fi le are:
[1, 'Geetika', 'F', 26]
Check Yourself :
MCQ:
1. _________file format are faster and easier for a prgram to read and write than other file
format.
34
a. Text file b. Binary file c. Doc file d. None of the above
Answer a. open()
Answer ⟵ a. close()
Answer a. ‘r’
5. _________ text file mode is used to append data in the file using file handling.
Answer c. ‘a’
6. 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+
Ans: b) wb+
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
35
c) File pointer is at beginning of file in wb mode and in wb+ at the end of file
d) No difference
Ans: a) wb mode is used to open binary file in write mode and wb+ mode open binary file
both for read and write operation.
Ans: d) dump()
d) None of these
a) r b) rb c) wb d) wb+
Ans: a) r
13. Which of the following function is used to read the data in binary file?
Ans: d) load()
14. 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
36
Ans: b) rb
15. This method returns an integer that specifies the current position of the file object.
ii. Both A and R are true but R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R 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: ii. Both A and R are true but R is not the correct explanation for A
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
3. Assertion(A): pickle.dump() function is used to store the object data to the file.
Ans: ii. Both A and R are true but R is not the correct explanation for A
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: i. Both A and R are true and R is the correct explanation for A
5. Assertion(A): ab+ mode is used for both appending and reading binary files and move file
pointer at end.
37
Reason(R): ab+ mode, if the file does not exist, it does not create a new file for reading and
writing.
(TRUE/FALSE Questions)
Ans: False
SA-2(3-Marks Questions)
1. 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
39
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
2. 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
3. A binary file named “EMP.dat” has some records of the structure [EmpNo, EName,
Post, Salary]. Create a binary file “EMP.dat” that stores the records of employees and
display them one by one. Also display the records of all those employees who are getting
salaries between 25000 to 30000.
Ans:
import pickle
f1 = open('emp.dat','rb')
try:
while True:
e = pickle.load(f1)
print(e)
except:
f1.close()
f1 = open('emp.dat','rb')
try:
while True:
e = pickle.load(f1)
if(e[3]>=25000 and e[3]<=30000):
print(e)
except:
f1.close()
4. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. Write a
function CountRec(Author) in Python which accepts the Author name as parameter and
count and return number of books by the given Author are stored in the binary file
“Book.dat”.
Ans:
import pickle
40
def CountRec(Author):
f=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load(f)
if Author==rec[2]:
num = num + 1
except:
f.close()
return num
5. Consider a binary file emp.dat having records in the form of dictionary. E.g {eno:1,
name:”Rahul”, sal: 5000} write a python function to display the records of above file for
those employees who get salary between 25000 and 30000.
Ans:
import pickle
def search():
f=open(“emp.dat”,”rb”)
while True:
try:
d=pickle.load(f)
if(d[‘sal’]>=25000 and d[‘sal’]<=30000):
print(d)
except EOFError:
break
f.close()
___________________ # statement 1
def addrecords():
fw= _____________ #statement 2
dict={}
ch=’y’
while ch==’y’:
eno=int(input(“enter employee number”))
nm= input(“enter employee name”)
sal=int(input(“enter employee salary”))
dict={‘empno’:eno,’name’:nm,’salary’:sal}
____________________ # statement 3
ch=input(“add more record”)
fw.close()
# function to diplay records
def display():
41
dict={}
fr= _____________ # statement 4
dict=____________ # statement 5
fr.close()
print(“data :”,dict)
Answer questions (i)-(v) based on above case study
(i). Help Ramesh to import the module to perform binary file operation in statement 1.
Ans: c) pickle
(ii). Which statement is used from the following for statement 2 to open the binary file in
write mode?
a) open(“employee.dat”,’w’) b) open(“employee.dat”,’wb’)
c) open(“employee.dat”,’w+’) d) open(“employee.dat”,’r’)
Ans: b) open(“employee.dat”,’wb’)
(iii). Which statement is used from the following for statement 3 to write dictionary data
created in above code, namely dict, is written in binary file employee.dat file?
a) pickle.dump(dict,fw) b) pickle.write(dict,fw)
c) pickle.save(dict,fw) d) pickle.store(dict)
Ans: a) pickle.dump(dict,fw)
(iv). Which statement is used from the following for statement 4 to open the binary file in
read mode?
a) open(“employee.dat”,’r’) b) open(“employee.dat”,’r+’)
c) open(“employee.dat”,’a’) d) open(“employee.dat”,’rb’)
Ans: d) open(“employee.dat”,’rb’)
(v). Compelete statement 5 to read data in dictionary namely dict from the opened
binary file?
a) dict=pk.read(fr) b) dict=pickle.load(fr)
Ans: b) dict=pickle.load(fr)
42
Case Study Based Question-2
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
43
UNIT -5 : DATA STRUCTURE ( STACK)
Stack: A stack is a data structure whose elements are accessed according to the Last-In First-Out
(LIFO) principle. This is because in a stack, insertion and deletion of elements can only take place
at one end, called top of the stack. Consider the following examples of stacks:
1. Ten glass plates placed one above another. (The plate that is kept last must be taken out first).
2. The tennis balls in a container. (You cannot remove more than one ball at a time)
3. A pile of books.
4. Stack of coins
The Significance of Stack Top : If we want to remove any coin from the stack, the coin on the top
of the stack has to be removed first. That means, the coin that In the above picture coins are kept one
above the other and if any additional coin is to be added, it can be added only on was kept last in the
stack has to be taken out first.
Note: Stack Work on LIFO (Last In First Out) principle.
Operations on Stack :
We can perform two operations on stack are: Push and Pop
#ans=1
while(True):
print("MENU \n 1-PUSH in STACK \n 2-POP \n 3-DISPLAY \n 4.exit \n")
ch=int(input("enter your choice 1-4"))
45
if(ch==1):
Push(s)
print("elemnets in stack after push operation",s)
if(ch==2):
Pop(s)
print("element in stack after pop",s)
if(ch==3):
display(s)
if(ch==4):
print("Thank You")
exit()
Stack implementation using list
s=[]
c="y"
while(c=="y"):
print("1. PUSH")
print( "2. POP ")
print("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Enter any number:")
s.append(a)
elif (choice==2):
if(s==[]):
print( "Stack Empty")
else:
print( "Deleted element is : ")
s.pop()
elif (choice==3):
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
else:
print("Wrong Input")
46
c=input("Do you want to continue or not? ")
MCQ:-
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
ANSWERS: 1. C 2. A 3. D 4.B 5. B
TRUE/FALSE:
1.LIFO stands for Last in First Out.
2. Can we perform Pop operation if stack is empty.
3. if size of stack is 5 can we Push 6 element in stack.
4. len() method used to find the size of stack.
5. Stack is a linear data structure.
ANSWERS: 1. T 2. F 3. F 4.T 5. T
Q1. 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}
47
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
Q2. 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):
48
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
Q3. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all
numbers divisible by 5 into a stack implemented by using a list. Display the stack if it has at
least one element, otherwise display appropriate error message.
ANSWER:
s=[25,40,27,34 ]
def PUSH(Arr,value):
for x in range(0,len(Arr)):
if(Arr[x]%5--0):
s.append(Arr[x])
if(len(s)==0):
print("Empty stack")
else:
print(s)
Q4. Write a function in Python POP(Arr), where Arr is a stack implemented by a list of numbers.
The function returns the value deleted from the stack.
ANSWER:
st=[2,3,6,8,10]
def popStack(st):
if(len(st)==0):
print('Underflow')
else:
49
L=len(st)
val=st[L-1]
print(val)
st.pop(L-1)
popStack(st)
Q5. Write functions in python for Push(List) and for PopS(List) for performing Push and Pop
operations with a stack of list containing integers.
ANSWER:
List=[1,2,3]
def PushS(List):
N=int(input('Enter Integer'))
List.append(N)
def PopS(List):
if (List==[]):
print('UnderFlow!!')
else:
print('Deleted Value: ',List.pop())
PushS(List)
print(List)
PopS(List)
Q6. 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:
50
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')
A ] Network Applications
Computer systems and peripherals are connected to form a network. They provide numerous
advantages:
• Resource sharing such as printers and storage devices
• Exchange of information by means of e-Mails and FTP
• Information sharing by using Web or Internet
• Interaction with other users using dynamic web pages
• Video conferences
• Parallel computing
• Instant messaging
NSFNET: in full National Science Foundation Network, used between 1985 to 1995 to
51
promote advanced research and education
Applications of Internet:
Following are some of the broad areas or services provided through Internet:
• The World Wide Web (WWW)
• Electronic mail (Email)
• Chat
• Voice over Internet Protocol (VoIP)
Concept of Communication: The term “Data Communication” comprises two words: Data
and Communication. Data can be any text, image, audio, video, and multimedia files.
Communication is an act of sending or receiving data. Thus, data communication refers to the
exchange of data between two or more networked or connected devices.
52
Sender: A sender is capable of sending data over a network. It can be a computer, mobile
phone, smartwatch, walkie talkie, video recording device, etc.
Receiver: A receiver is capable of receiving data from the network. It can be any computer,
printer, laptop, mobile phone, television, etc. In computer communication, the sender and
receiver are known as nodes in a network.
Message: It is the data or information that needs to be exchanged between the sender and the
receiver. Messages can be in the form of text, number, image, audio, video, multimedia, etc.
Communication media: It is the path through which the message travels between source and
destination. It is also called medium or link which is either wired or wireless. For example, a
television cable, telephone cable, ethernet cable, satellite link, microwaves, etc.
Protocols: It is a set of rules that need to be followed by the communicating parties in order to
have successful and reliable data communication.
3] DATA : Data means information in digital form which is stored processed and exchanged
between digital devices like computer, mobile phones or laptop. Data can be text, image, audio,
video or multimedia files. Computers stores raw data and process these data into meaningful
information. Hence,
we can define Information as processed data.
4] COMMUNICATION
The exchange of information between two or more networked or interconnected devices is
called communication. These devices must be capable of sending /receiving data over a
communication medium.
53
5] COMPONENTS OF DATA COMMUNICATION
message
Sender < - Transmission channel ->
RECEIVER
message
54
Megabits per second (Mbps) or Gigabits per second (Gbps).
9] IP ADDRESS
IP address or Internet Protocol address is a unique numeric logical address assigned to every
device connected to a network.
It uniquely identifies every node connected to a local network or internet.
An IP address allows computers to send and receive data over the internet. They can also
be used to track down a user's physical location.
• There are two versions for IP address IPV4 and IPV6.
• IP addresses are binary numbers but are typically expressed in decimal form
(IPv4 – 4 byte ) or hexadecimal form (IPv6 – 16 byte ) to make reading and using them
easily.
• The commonly used IP address is IPV4.
• An IPv4 address consists of four numbers, each of which contains one to three digits,
with a single dot (.) separating each set of digits.
• Each of the four numbers can range from 0 to 255.
• Example IP address: 24.171.248.170
55
2. Packet Switching
In the packet switching technique, the whole message is split into small packets. Now, these
packets are transmitted one by one from sender to the receiver through the intermediary
switches in the network. The packets will take shortest path as possible.
Every packet will have a sequence number in order to identify their order at the receiving end.
The packets will also contain information like source address, intermediate node address,
destination address etc.
8] Transmission media
Transmission media is a communication channel that carries the information from the sender to
the receiver.
1. Coaxial Cable:
- Advantages:
Good bandwidth and data transmission rates , Suitable for both short and long-distance
connections , Durable and resistant to interference.
- Disadvantages:
Bulky and less flexible than other cables , More expensive than twisted-pair cables.
Susceptible to signal degradation over long distances.
2. Twisted-Pair Cable (Ethernet Cable):
- Advantages:
Widely used for LAN connections, Cost-effective and easy to install ,
Available in various categories (e.g., CAT5e, CAT6) for different data rates.
56
- Disadvantages: Limited in terms of maximum distance, Susceptible to electromagnetic
interference (EMI) and crosstalk.
3. Fiber-Optic Cable:
- Advantages: Exceptional data transmission speeds and bandwidth,Immune to EMI and
signal loss over long distances, Ideal for high-demand applications and long-haul connections.
- Disadvantages: Expensive to install and maintain, Fragile and sensitive to bending.,
Requires specialized equipment for termination and splicing.
The choice of wired network media depends on specific requirements, such as data speed,
distance, cost, and susceptibility to interference. Businesses and individuals typically select the
medium that best aligns with their networking needs and budget. It's worth noting that
advancements in technology have resulted in wireless solutions like Wi-Fi becoming more
prevalent, especially for mobility and flexibility in network connectivity.
The electromagnetic spectrum range (3KHz to 900THz) can be divided into 4 categories (Radio
waves, Microwaves, Infrared waves and Visible or Light waves) according to their frequency
ranges.
57
Infrared waves 1. Electromagnetic waves of frequency range 300GHz - 400THz.
2. Very high frequency waves.
3. Cannot penetrate solid objects such as walls.
4. Used for short-distance point-to-point communication such as mobile-
to-mobile, mobile-to-printer, remote-control-to-TV, and Bluetooth-
enabled devices to other devices like mouse, keyboards etc.
1. Modem:
Stands for "modulator-demodulator.",Converts digital data from a computer into
analog signals for transmission over telephone lines or cable systems. Also, it converts
incoming analog signals back into digital data for the computer.
2. Ethernet Card: Also known as a network interface card (NIC)., Enables a computer
to connect to an Ethernet network using Ethernet cables, Essential for wired network
connections.
5. Hub:
A basic networking device that connects multiple devices in a network, Broadcasts data
to all connected devices, causing network congestion and inefficiency.
6. Switch:
Intelligent device that connects devices in a network, Forwards data only to the device
that needs it, improving network performance and efficiency.
7. Router:
Manages traffic between different networks, such as your home network and the
internet, Performs functions like assigning IP addresses, directing data, and providing
security.
8. Gateway:
- Acts as an entry and exit point for data traveling between different networks or
protocols, Translates data between different formats or protocols to ensure smooth
communication.
9. Wi-Fi Card:
- A wireless network adapter that allows a computer to connect to Wi-Fi networks.
58
- Commonly found in laptops and mobile devices for wireless internet access
PAN (Personal Area Network) is a computer network formed around a person. It generally
consists of a computer, mobile, or personal digital assistant. PAN can be used for establishing
communication among these personal devices for connecting to a digital network and the
internet.
Features of PAN
Below are the main Features of PAN:
A Local Area Network (LAN) is a group of computer and peripheral devices which are
connected in a limited area such as school, laboratory, home, and office building. It is a widely
useful network for sharing resources like files, printers, games, and other application. The
simplest type of LAN network is to connect computers and a printer in someone’s home or
office.
Features of LAN:-
Here are the important characteristics of a LAN network:
Features of MAN:-
59
Here are important characteristics of the MAN network:
WAN (Wide Area Network) is another important computer network that which is spread across
a large geographical area. WAN network system could be a connection of a LAN which
connects with other LAN’s using telephone lines and radio waves. It is mostly limited to an
enterprise or an organization.
Features of WAN
Below are the characteristics of WAN:
• The software files will be shared among all the users; therefore, all can access to the
latest files.
• Any organization can form its global integrated network using WAN.
1. Star Topology:
- Working: In a star topology, all devices are connected to a central hub or switch. Data flows
through the central hub, which manages the communication between devices.
- Advantages: Easy to set up and manage, Isolation of network issues - a problem with one
device does not affect others, Scalability - easy to add or remove devices.
- Disadvantages: Dependency on the central hub - failure of the hub disrupts the entire
network, Costlier due to the need for the central hub.
2. Bus Topology:
- Working: In a bus topology, all devices are connected to a single central cable, and data is
transmitted linearly.
- Advantages: Simple and cost-effective for small networks,Easy to install and extend.
- Disadvantages: Susceptible to cable failure - if the main cable breaks, the entire network
goes down, Performance degrades as more devices are added.
3. Ring Topology:
- Working: In a ring topology, each device is connected to exactly two other devices, creating
a closed loop. Data travels in one direction around the ring.
- Advantages: Equal data transmission opportunities for all devices,No collisions in data
transmission.
- Disadvantages: A break in the ring can disrupt the entire network, Adding or removing
60
devices can be complex.
4. Mesh Topology:
- Working: In a full mesh topology, every device is connected to every other device. In a
partial mesh, only critical devices are connected to each other.
- Advantages: High redundancy and fault tolerance, Direct, efficient communication paths.
- Disadvantages: Complex and expensive to implement, especially in a full mesh, Difficult to
manage and scale in large networks.
5. Hybrid Topology:
- Working: A hybrid topology combines two or more different topologies, often connecting
smaller topologies to a larger one.
- Advantages: Customizable to meet specific network needs,Balances the strengths and
weaknesses of different topologies.
- Disadvantages: Complex to design and manage, Can be costly to implement.
There are various types of network protocols that support a major and compassionate role in
communicating with different devices across the network.
Network protocols are essential for enabling communication and data exchange in computer
61
networks. Here's a brief explanation of the roles of some important network protocols:
7. Post Office Protocol (POP) and Internet Message Access Protocol (IMAP):
- Role: POP and IMAP are used by email clients to retrieve messages from a mail server.
IMAP allows messages to be stored on the server, while POP downloads them to the client.
62
11. Simple Network Management Protocol (SNMP):
- Role: SNMP enables the monitoring and management of network devices. It provides a
standardized way to collect information about network performance, detect issues, and make
configuration changes.
Web services are an integral part of the modern internet ecosystem, enabling communication
and data exchange over the World Wide Web (WWW). Here's an introduction to key concepts
and components related to web services:
63
Domain Names:
• Domain names are human-friendly labels used to identify websites on the internet.
• They provide a way to access web resources using easy-to-remember names, such as
"www.example.com."
URL (Uniform Resource Locator):
• A URL is a web address that specifies the location of a resource on the internet.
• It consists of various components, including the protocol (e.g., "http" or "https"), domain
name, path, and optional query parameters.
Website:
• A website is a collection of related web pages and resources that are accessible on the
internet.
• It can serve various purposes, including providing information, offering services, or
hosting web applications.
Web Browser:
• A web browser is a software application that allows users to access and interact with
web content.
• It renders HTML and other web technologies, displaying web pages and handling user
interactions.
Web Servers:
• Web servers are software or hardware components that store and deliver web content to
clients, such as web browsers.
• They respond to requests from clients by sending the requested web pages and data.
Web Hosting:
• Web hosting involves the storage and management of web content on servers that are
accessible via the internet.
• Web hosting providers offer various hosting services, including shared hosting, VPS
hosting, and dedicated hosting, to host websites and web applications.
MCQ Questions
64
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. When first network was came into existence?
a. 1969 b. 1972 c. 1975
d. 1977
7. ARPANET used the concept of packet switching network consisting of subnet
and…………… computers.
A) local B) remote C) host
D) network
8. ARPANET was developed by the ARPA(Advanced Research Project Agency)
in……………….. which is the research arm of DOD.
A) 1968 B) 1966 C) 1969
D) 1967
9. ………… is a globally existing network of networks consisting of a huge number of
computers situated in all the parts of the world?
12. IP Address is a :
a. unique logical address b. unique physical address
c. is same as MAC address d. is of 6 bytes
13. The valid IP address is :
65
a. 192.168.111 b.192.168.1.121
c.192:1:112:67 d.192_1_168_1_121
14. Correct unit of data transfer rate in communication is /are :
a. Kbps b. Mbps
c. Gbps d. All of the above
15. 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\
16. 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 .
17. A local telephone network is an example of a _______ network
a. Packet Switching b.Circuit Switching
c. Message Switching d. None of the above
18. In which type of switching technique physical link is first established between the source
and the destination:
a. Packet Switching b.Circuit Switching
c.Message Switching d.None of the above
19. In which type of switching technology Multiple users can share the channel simultaneously
utilizing the bandwidth effectively.
a. Packet Switching b. Circuit Switching
b. Message Switching d. None of the above
20. Most packet switches use this principle ____________
a) Stop and wait b) Store and forward
c) Store and wait d) Stop and forward
21. The process of selecting a path of data out of the available paths is called :
a. Transferring data b. Accessing data
c. Switching d. Routing
22. 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
66
c. Fibre optic d. Radio wave
26. 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
32. Which of the following connector is used to attach the ethernet cable?
a. RC Connector. b. T Connector
c. RJ45 Connector. d. E Connector
33 Fill in the blank:
The modem at the sender’s computer end acts as a ____________.
a. Model b. Modulator c. Demodulator d. Convertor
67
34.Which one of the following network devices transmits the data in the form of packets?
a. Router b.Bridge c.Both a and b d.None of the above
35. Which one of the following network devices is the broadcast device?
a. Hub b.Router c.Both a and b d.None of the above
36.Which one of the following network devices is used to create a network?
a. Hub b. Switch c. Router d.None of the above
37.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
38. Which of the following device an interface between computer and network?
a.Modem b.Router c.Ethernet Card. d.Repeater
39.Which one of the following network devices is not an intelligent device?
a. Hub b.Switch c.Router d. None of the above
40. Which one of the following network devices uses bits or electrical signals to send the data?
a. Hub. b. Switch. c. Router. d.Both b and c
41. The function of a repeater is to take a weak and corrupted signal and it.
a) Restore. b) Regenerate. c) Amplify. d) Reroute
45.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
46._____is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) VoIP (B) SMTP (C) PPP (D) HTTP
50. Which protocol holds the email until you actually delete it?
(A)POP3 (B)IMAP (C)SMTP (D) FTP
52. The protocol suit that is the main communication protocol of over the internet
(A)HTTP. (B)FTP C) TCP/IP (D)PPP
53. Which protocol holds the email only until you receive it ?
(A)SMTP (B)FTP (C)IMAP (D)POP3
54. What out of the following ,will you use to have an audio visual chat with an expert sitting
in a far away place to fix up a technical issue?
(A)VoIP. (B) SMTP (C)PPP (D)FTP
56. Which markup language is used for creating the structure of web pages?
A) CSS B) HTML C) XML D) JavaScript
57.Which markup language is primarily used for defining data structures and encoding
data?
A) HTML B) CSS C) XML D) JavaScript
61. 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
62.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
69
C) Accessing domain names D) Hosting websites
Answers :
MCQ questions:
1- D 2.B 3.A 4C 5.E 6A 7C 8A 9C 10A 11C 12A 13B 14D 15A 16C 17B 18B 19A
20B 21C 22Answer: a) Micro wave 23Answer: c) Nodes 24 Answer: b) Channe 25 Answer: a)
Channel 26Answer: a) Transmission media 27Answer: d) All Mentioned Above 28Answer: a)
Fibre Based Network 29Answer: d) a & b both 30Answer: 31b)Answer: d) a & b both
32ANS-c 33ANS- 34ANS-c 35 ANS-a 36ANS-b 37ANS-a 38ANS-c 39 ANS-a 40 ANS-a
41ANS-b 42Ans a 43B 44B 45Ans : VoIP 46 A)VoIP 47 D)HTTP 48B)Hyper text transfer
protocol 49 D)Downloading email 49 Ans : IMAP 50 C 51TCP/IP 52D 53VoIP 54C) World
Wide Web 55 B) HTM 56C) XML 57 A) To specify the web server's IP address 58D) Path
59 C) Web browsers and web servers 60 C) Web browser 61B) Storing web content 62 C)
Storing and serving web content 63D File Extension
Answers :
Q1. Nidhi is confused between bandwidth and data transfer rate . Help her to understand the
same .
Bandwidth Data transfer rate
70
Difference in highest and lowest frequency No. of bits transferred per unit of time
of signals in a network
Unit : Htz Unit : Mbps , Kbps
Q2. Write any one difference between circuit switching and packet switching .
Ans: IP address or Internet Protocol address is a unique logical 4byte address . Example:
71
192.168.1.190
Ans: 1. Time required to setup a physical connection between the sender and the receiver
Answer : False
72
Q1) Assertion: Wireless technologies allow communication between two or more devices in
short to long distance without requiring any physical media.
Reason: Wireless technologies allow communication between two or more devices in
short to long distance without requiring any physical media..
Answer: (b) Both A and R are true and R is not the correct explanation for A
Q2) Assertion: It is necessary to use satellites for long distance T.V transmission.
Reason: The television signals are low frequency signals.
Answer: (c) A is true, but R is false.
Q3) Assertion: It is not necessary for a transmitting antenna to be at the same height as that of
receiving antenna for line-of sight communication.
Reason: If the signal is to be received beyond the horizon then the receiving antenna must
be high enough to intercept the line-of sight waves.
Answer: (a) Both A and R are true and R is the correct explanation for A.
Q4) Assertion: Microwave propagation is better than the sky wave propagation.
Reason: Microwaves have frequencies 100 to 300 GHz, which have very good
directional properties.
Answer: (a) Both A and R are true and R is the correct explanation for A.
Q5) Assertion: Satellite is an ideal platform for remote sensing.
Reason: Satellite in polar orbit can provide global coverage or continuous coverage of
the fixed area in geostationary configuration.
Answer: (a) Both A and R are true, and R is the correct explanation for A.
a)
statement 1:- Modem is used for conversion between electric signals and digital bits..
statement 2:- Each NIC has a MAC address
ANS-a
b)Statement :1- A switch can work is place of a hub.
Statement 2:- A gateway is like a modem.
73
ANS-b
c) Statement :1 A switch is a device used to segment networks into sub-networks or subnets.
Statement :2 A switch does not forward the signals which are noisy or corrupted.
ANS-a
d) Statement 1 – A router can not connect LAN with WAN
Statement 2 - A router works as a dispatcher and choose the most efficient route for data
packets to travel across a networ
ANS-d
e.Statement :1- A repeater is an analog device.
Statement :2:- A modem is neither analog nor digital it is a converting device
Ans: a
3. Assertion: HTML and XML serve the same purpose and can be used interchangeably for
creating web content.
Reason: Both HTML and XML are markup languages designed for structuring web
content.
Answer: (b) Both A and R are true and R is not the correct explanation for A
4. Assertion: Web hosting providers are responsible for the security and encryption of
data transmitted between web browsers and web servers.
Reason: Security and encryption of data are primarily the responsibility of web browsers.
Answer: (d) A is false, but R is true.
5.Assertion: The World Wide Web (WWW) is synonymous with the internet.
Reason: WWW is a term often used interchangeably with the internet.
Answer: (b) Both A and R are true, but R is not the correct explanation for A.
6. Assertion: A URL is a specific web address that always starts with "www."
Reason: The "www" prefix is a mandatory part of every URL.
Answer: (d) A is false, but R is true.
7. Assertion: HTML documents can be executed directly in a web browser.
Reason: Web browsers interpret and render HTML code to display web pages.
Answer: (a) Both A and R are true, and R is the correct explanation for A.
74
Q1) Define communication channel.
Answer: A communication channel is the medium through which data is moved from the
source to destination. The communication channel can be either wired or wireless. Wired
communication channel is also called guided medium while wireless communication channel
is also called unguided medium.
Q2) 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.
Q3) Differentiate between communication using Optical Fiber and Ethernet Cable in
context of wired medium of communication technologies.
Answer: Optical Fibre - Very Fast - Expensive - Immune to electromagnetic interference
Ethernet Cable - - Slower as compared to Optical Fiber - Less Expensive as compared to
Optical Fiber - prone to electromagnetic interference.
Q4) 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.
Q5) 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).
75
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.
Q8) What is the difference between switch and router?
ANS-
SN Switch Router
1 it works on the same network type It works on network of a different type.
2 They are found in the same LAN They connect LANs and there can be
where there is a single path from multiple paths from source to destination
source to destination
76
Answer: 1)Both protocols TCP and UDP are used to send bits of data over the Internet, which
is also known as ‘packets’.
2)When packets are transferred using either TCP or UDP, it is sent to an IPaddress. These
packets are traversed through routers to the destination.
Q13)What is a protocol?Which protocol is used to search information from internet using an
internet browser?
Answer: Protocols are a set of rules outlining how connected devices communicate across a
network to exchange information easily and safely.
HTTP protocol is used to search information from internet using an internet browser.
Q15)Define IMAP?
Answer:Internet Message Access Protocol, or IMAP, is a standard email retrieval (incoming)
protocol. It stores email messages on a mail server and enables the recipient to view and
manipulate them as though they were stored locally on their device(s).
77
Answer: The main function of a web browser is to display web content and allow users to
interact with it.
Answer:Telnet is a set of rules designed for connecting one system with another. The connecting
process here is termed as remote login. The system which requests for connection is the local
computer, and the system which accepts the connection is the remote computer.
78
Answer : 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:
Q6)What protocol can be applied when you want to transfer files between different platforms,
such as UNIX systems and Windows servers?Expand TCP.
Answer: We can use FTP (File Transfer Protocol) for file transfers between such different
servers. This is possible because FTP is platform-independent.
TCP - TRANSMISSION CONTROL PROTOCOL
Q7)(a) Write the full forms of the following: (i) SMTP (ii) PPP (b) What is the use of TELNET?
Answer: a)SMTP -Simple mail transfer protocol ii)PPP- Point to point protocol
TELNET : Telnet is a set of rules designed for connecting one system with another
Q9): 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.
Q10) Explain the role of HTML in web development. How does HTML structure web
content, and what are its basic elements?
Answer: HTML (Hyper Text Markup Language) is a fundamental language for web
development. It structures web content by using tags to define elements such as headings,
79
paragraphs, lists, links, images, and more. HTML provides a standardized way to format and
arrange content on web pages, making it accessible to web browsers for rendering.
Q11) How does XML differ from HTML, and what are its primary use cases in web
services
and data management?
Answer: XML (Extensible Markup Language) differs from HTML in that it is not
focused on presentation but rather on data storage and exchange. XML allows users to define
their own tags, making it a versatile choice for structuring and encoding data in a machine-
readable format. Its primary use cases include data interchange, configuration files, and
representing structured information in a human-readable and machine-readable format.
Q12) What are domain names, and why are they essential in web services? Explain the
domain name system (DNS) and how it resolves domain names to IP addresses.
Answer: Domain names are human-readable web addresses that simplify access to
resources on the internet. The Domain Name System (DNS) is a distributed database that
translates domain names into IP addresses, which are required to locate resources on the internet.
When a user enters a domain name in a web browser, the DNS system resolves it to the
corresponding IP address, allowing the browser to connect to the appropriate web server.
Q13) Describe the components of a URL (Uniform Resource Locator) and their
significance in identifying and accessing web resources.
Answer: A URL consists of several components, including the protocol (e.g., "http" or
"https"), domain name or IP address, port number, path, and query parameters. These
components work together to specify the exact location of a web resource. The protocol
determines how the resource should be accessed, while the domain name or IP address identifies
the server hosting the resource. The path and query parameters further specify the resource's
location and parameters.
Q14) What constitutes a website, and how do websites function on the internet? Explain
the role of web servers and web browsers in the process.
Answer: A website is a collection of web pages and related content accessible under a
common domain name. Websites are hosted on web servers, which store and serve web content
to users upon request. Web browsers, such as Chrome or Firefox, act as client applications that
80
send requests to web servers to access web pages. Browsers interpret HTML and other web
technologies to display web content to users.
(i) Suggest the most appropriate block, where RCI should plan to install the server.
81
(ii) Which type of network out of the following is formed by connecting the computers of these
three blocks?
6. LAN
7. MAN
8. WAN
(iii) Which wireless channel out of the following should be opted by RCI to connect to students
from all over the world?
9. Infrared
10. Microwave
11. Satellite
Answer. (i) Faculty Studio Building: As it has the maximum number of computers
(ii) LAN
(iii) Satellite
Q2) Global Pvt. Ltd. is setting up the network in the Bangalore . There are four
departments
82
Number of Computers
(ii) Suggest the most suitable place (i.e. buildings) to house the server of this
organization.
(iii) Suggest the placement of the following device with justification:
a) Repeater b) Hub/Switch
(iv) Suggest the best Transmission media to connect the devices of each block.
Q3. Rajlakshmi is a class 12 computer science student. She is confused between the working of
'switch ' and 'router '. As a friend of Rajlakshmi, explain her the difference between the working
of swich and router .
ANS-, A router’s main objective is to establish a connection between networks of different
types . Also, it works on the network layer. A switch’s main objective is to establish a connection
among various devices of the same network . It basically functions on the data link layer.
83
Q4. Mr Anshuman is running an academic Institute which has various blocks(buildings). H e is
planning to set up a network . He is confused in installation of network devices like Hub/Switch
and Repeater. Which device will you suggest to be placed/installed in each of these blocks to
efficiently connect all the computers within these blocks
ANS-
i. Hub/Swich to be placed in each building block .
(v) Repeater is to be placed between the blocks if distance between the blocks is
more than 80m
Q5. Raj has set up an Institute with four specialised departments for Orthopedics,
Neurology and Pediatrics along with an administrative office in separate buildings. In
the same campus .Suggest the devices to be installed in each of these offices for connecting
computers installed within the building out of the following:
∙ Modem
∙ Switch
∙ Gateway
∙ Router
Q6.
84
Answer:
i)Proper Layout using Star or Bus topology preferably.
ii)Hub/Switch
iii)Admin
iv)Satelite
v)No need of Repeater
Q7.Xclencia Edu Services Ltd. Is an educational organization. It is planning to set up its India
campus at Hyderabad with its head office at Delhi. The Hyderabad campus has 4 main
buildings – ADMIN, SCIENCE, BUSINESS and ARTS. You as a network expert have to
suggest network related solutions for their problems raised in (i) to (iv), keeping in mind the
distances between the buildings and other given parameters.
85
ADMIN to SCIENCE 65m
ADMIN to BUSINESS 100m
ADMIN to ARTS 60m
SCIENCE to BUSINESS 75m
SCIENCE to ARTS 60m
BUSINESS to ARTS 50m
DELHI head Office to HYDERABAD 1600km
Campus
ADMIN 100
SCIENCE 85
BUSINESS 40
ARTS 12
DELHI Head Office 20
(i) Suggest the most appropriate location of the server inside the HYDERABAD campus (out
of the 4 buildings), to get the best connectivity for maximum number of computers. Justify
your answer.
(ii) Suggest and draw the cable layout to efficiently connect various buildings within the
HYDERABAD campus for connecting the computers.
(iii) Which hardware device will you suggest to be procured by the company to be installed to
protect and control the internet uses within the campus?
(iv) Which of the following will you suggest to establish the online face-to-face
communication between the people in the Admin Office of HYDERABAD campus and
DELHI Head Office?
a.E- Mail
b.Text Chat
c.Video Conferencin
d.Cable TV
(V)Is there any requirement of repeater in the selected layout?Explain.
Answer :
i)ADMIN
i)Proper Layout using Star ,Ring or Bus topology preferably.
iii)Firewall
iv)Video Conferencing
v)May be given between Admin to Business Block.
Q8. Great Sudies University is setting up its Academic schools at Sunder Nagar and planning
to set up Network. The university has 3 academic schools and one administration centre s
shown in the diagram below:
86
Centre to centre distances between various buildings is as follows:
i)Suggest the most suitable most suitable place (i.e. School/Centre) to install the server of this
university with a suitable reason.
ii)Suggest an ideal layout for connecting these schools/center for a wired connectivity.
iii)Which device will you suggest to be placed/installed in each of these schools/center to
efficiently connect all the computers within these schools/centre ?
iv)The university is planning to connect its admission office in the closest big city, which is
more than 350 km from the university. Which type of network out of LAN, MAN or WAN
will be formed ? Justify your answer.
v) In which block modem is to be placed?Justify your answer.
Answer :
i)Admin Centre
ii) Proper Layout using Star ,Ring or Bus topology preferably
iii)Hub/Switch
iv)WAN
v)Admin Centre
Q9. “Vidhya for All” is an educational NGO. It is setting up its new campus at Jaipur for its
web- based activities. The campus has four buildings as shown in the diagram below:
87
Center to the center distances between various buildings as per architectural drawings (in
meters) is as followings:
MAIN BUILDING TO RESOURCE BUILDING 120m
MAIN BUILDING TO TRAINING BUILDING 40m
MAIN BUILDING TO ACCOUNTS BUILDING 135m
Answer :
88
iii)Where the distance more than 90-100 mtr .
iv)Optical fibre
v)Firewal
89
7. RELATIONAL DATABASE - Relational Database consists of various Tables which
are also known as Relations.
8. TABLES/RELATIONS – A Table or a Relation consists of several Rows or Tuples
which hold the Records.
9. ROWS/TUPLES – A Row or Tuple consists of several Columns or Attributes with
various Data Fields to store Interrelated Data.
10. COLUMNS/ATTRIBUTES – Each Attribute or Column contains Data which are to
be stored in the Relation.
11. ENTITY – An Entity is the Data that is stored in each column/ attribute.
12. DOMAIN OF A RELATION – Domain refers to the data that can be inserted in a
specific column/ attribute.
1) Eg. Gender Attribute can hold only (M/F/O) Data and any other data will be
treated as Outside the Domain of this attribute.
13. DEGREE OF A RELATION – The total number of Attributes in a relation is known
as the Degree of the Relation.
14. CARDINALITY OF A RELATION – The total number of Tuples / Records in a
relation (excluding the Top Row, which contains the Attribute Headers) is known as
the Cardinality of the Relation.
1)
15. KEYS IN A DATABASE
16. PRIMARY KEY – An Attribute or a set of Attributes, which uniquely identifies each
tuple in the Relation is known as Primary Key.
17. CANDIDATE KEY – An Attribute or a set of Attributes that has the ability to
uniquely identify each tuple in the Relation is known as a Candidate Key.
18. ALTERNATE KEY – All the Candidate Keys which were not chosen to be Primary
Key are also known as Alternate Keys.
19. FOREIGN KEY - An Attribute or a Set of Attributes in one relation which refer to
the Primary Key of any other Relation is known as the Foreign Key of the Relation.
They are used to establish relationships between Tables.
Tips to Remember regarding Keys in a Database
One can always relate the Keys in a Relation to be like the Representatives of Each Political
Party during an Election.
• All representatives are those who promise to uniquely identify the problems of each
voter in the country. They are the Candidates for the Election. In a similar way,
Candidate Keys can uniquely identify each tuple.
• After the Elections One Candidate among all the Candidates are elected as the Prime
Minister of the Country. Similarly any one of the Candidate Keys which has been
90
chosen by the Database Developer to uniquely identify each tuple is the Primary Key
of the Relation.
• All those Candidates who could not become the Prime Minister, become the member of
the Opposition. Similarly all the Candidate Keys which were not chosen to be Primary
Key are also known as Alternate Keys of the Relation.
• The Prime Minister of the Country often sends Foreign Ministers to represent the
Prime Minster in other countries. Similarly, a Foreign Key are attributes in a relation
which refers to the Primary Key of some other Relation.
91
Answer: (A)
Question 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).
Question 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).
Question 3:
Assertion (A): A relation in the relational data model is a set of tuples.
92
Reason (R): A tuple is a column in a table.
Answer: Assertion (A) is True and Reason (R) is False.
Question 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).
Question 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).
93
4.Given a Table Employee (EID, EName, Department, Salary). The Table contains details
of 10 Employees. A User inserts 4 more Employee records. 2 Employees resign and their
data are deleted from the table. The developer also adds a Gender Column to the table.
What is the Degree and Cardinality of the Table? Also mention which column can be used
as a Primary Key.
Ans. Degree – 5 and Cardinality – 12 , Primary Key – EID
5.Differentiate between Primary Key and Foreign Key.
Ans. An Attribute or a set of Attributes, which uniquely identifies each tuple in the Relation is
known as Primary Key whereas an Attribute or a Set of Attributes in one relation which refer to
the Primary Key of any other Relation is known as the Foreign Key of the Relation. They are
used to establish relationships between Tables. There can only be 1 Primary Key however, there
can be multiple Foreign Keys from multiple Tables.
94
12. The manipulation includes inserting data into tables, deleting data from the tables,
retrieving data and modifying the existing data.
13. The common DML statements are SELECT, UPDATE, DELETE and INSERT.
(2) VARCHAR:
18. VARCHAR is a variable character string.
19. Syntax: VARCHAR (n)
20. Variable-length character string having maximum length n.
21. Example: VARCHAR(5) means a maximum of 5 characters can be stored but the
actual allocated bytes will depend on the length of entered string. So ‘CS’ in
VARCHAR(5) will occupy space needed to store 2 characters only.
(3) INT:
22. INT specifies an integer value.
23. Each INT value occupies 4 bytes of storage.
24. This used to store integer number (without any fractional part).
25. Syntax: INT
(4) FLOAT:
• This data type is used to store number with decimal points.
• Each FLOAT value occupies 4 bytes.
• Syntax: FLOAT
(5) DATE:
• The DATE type is used for dates in 'YYYY-MM-DD' format.
• YYYY is the 4 digit year, MM is the 2 digit month and DD is the 2 digit date.
• The supported range is '1000-01-01' to '9999-12-31'.
• Syntax: DATE
Constraints:
• Constraints are certain types of restrictions on the data values that an attribute can
have.
• They are used to ensure the accuracy and reliability of data.
• However, it is not mandatory to define constraint for each attribute of a table.
Types of Constraints:
• NOT NULL - Ensures that a column cannot have NULL values where
NULL means
• missing / unknown / not applicable value.
95
• 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.
CREATE Database:
• It is used to create a database
• Syntax: CREATE DATABASE <DatabaseName>;
• Example : CREATE DATABASE School;
USE Database:
• The USE statement of MySQL helps to select/use a database.
• USE statement is also used to change to another database.
• Syntax: USE <DatabaseName>;
• Example: USE School;
Database is changed to school.
CREATE TABLE : It defines the relations in a database and specify attributes for each
relation along with data type and constraint (if any) for each attribute.
Syntax:
CREATE TABLE<table name>
(<column name1> <data type>[size][constraints],
<column name2> <data type>[size][constraints],
…
<column name n> <data type>[size][constraints]);
• ALTER TABLE : It is used to make changes in the structure of a table like adding,
removing or changing datatype of column(s).
• Syntax :
• ALTER TABLE <TableName> ADD/MODIFY/DROP
<Attributes/Datatype/Constraints>;
▪ To add NOT NULL / UNIQUE / PRIMARY KEY Constraint
ALTER TABLE <TableName> MODIFY <ColumnName>
<DATATYPE(SIZE)> Constraint;
• To remove NOT NULL Constraint
ALTER TABLE <TableName> MODIFY <ColumnName>
<DATATYPE(SIZE)>;
• To remove UNIQUE Constraint
ALTER TABLE <TableName> DROP INDEX <ColumnName>;
• To remove PRIMARY KEY Constraint
ALTER TABLE <TableName> DROP PRIMARY KEY;
• To add a column to an existing table
ALTER TABLE <TableName> ADD <ColumnName> <DATATYPE(SIZE)>
<Constraint>
96
• To remove a column from an existing table
ALTER TABLE <TableName> DROP <ColumnName>;
• To change the data type a column from an existing table
ALTER TABLE <TableName> MODIFY <ColumnName>
<DATATYPE(SIZE)>;
• DROP TABLE : To remove a table permanently from the database.
Syntax : DROP TABLE <TableName>;
97
6. “The column which can uniquely identify each row or record in a table.”
The above Statement refers to which constraints in MySQL ?
LL. NOT NULL
MM. UNIQUE
NN. PRIMARY KEY
OO. DEFAULT
7. Identify the Statement which is NOT CORRECT ?
PP. It is mandatory to define constraint for each attribute of a table.
QQ. Constraints are certain types of restrictions on the data values that an
attribute can have.
RR. Constraints are used to ensure the accuracy and reliability of data.
SS. 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.
TT. CREATE TARGET100;
UU. CREATE DATABASE TARGET100;
VV. CREATE DATABASES TARGET100;
WW. 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.
XX. GO TO DATABASE RECORD;
YY. USE DATABASE RECORD;
ZZ. CHANGE DATABASE RECORD;
AAA. 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
mysql>
BBB. She has to first USE an available database or create a new database and
then USE it.
CCC. Wrong syntax for CREATE TABLE
DDD. Wrong data type declaration
EEE. PRACTCAL named table already exists.
ASSERTION - REASONING
Q.11, 12, 13, 14 and 15 are ASSERTION(A) AND REASONING(R) based questions.
Mark the correct choice as
FFF. Both A and R are true and R is the correct explanation for A
GGG. Both A and R are true and R is not the correct explanation for A
98
HHH. A is True but R is False
III. A is false but R is True
A table REMEDIAL is created with following attributes, datatype and constraints:
Field Datatype Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
12. Assertion(A):
The MySQL statement :
INSERT INTO REMEDIAL VALUES ('PAROMITA DOGRA', 10, 3000, 5500);
will generate an ERROR and record will not be inserted.
Reasoning(R):
Duplicate entry '10' for the field 'ROLL'. The Constraint assign is UNIQUE which
restricts the duplicate entry.
13. Assertion(A):
The MySQL statement :
INSERT INTO REMEDIAL (SNAME, ROLL, ADMN) VALUES ('NANDAN
VERMA', 20, 6850);
will generate an ERROR and record will not be inserted.
Reasoning(R):
No data may be assigned for the field FEES as it has no constraints.
14. Assertion(A):
The MySQL statement :
INSERT INTO REMEDIAL VALUES ('NEHA JAIN', 25, 3500, 4585);
will generate an ERROR and record will not be inserted.
Reasoning(R):
Duplicate entry '3500' for the field 'FEES'.
15. Assertion(A):
The MySQL statement :
99
INSERT INTO REMEDIAL VALUES ('NEHA JAIN', 25, 3500, 4585);
will generate an ERROR and record will not be inserted.
Reasoning(R):
Duplicate entry '4585' for the field ADMN. The Constraint assign is PRIMARY KEY
which restricts the duplicate entry.
True False
State True or False for Q.16 to Q20:
100
Answer :
MCQ
1. (A)
2. (C)
3. (C)
4. (A)
5. (C)
6. (C)
7. (A)
8. (B)
9. (A)
10. (A)
11. (A)
12. (A)
13. (D)
14. (B)
15. (A)
16. True
17. False
18. False
19. True
20. True
21. i. CREATE DATABASE SCHOOL;
ii.
CREATE TABLE REMEDIAL(
SNAME VARCHAR(20) NOT NULL,
ROLL INT UNIQUE,
FEES FLOAT
ADMN INT PRIMARY KEY);
22. ALTER TABLE STUDENT ADD ADMN INT PRIMARY KEY;
23. ALTER TABLE STUDENT DROP GENDER;
ALTER TABLE STUDENT ADD FEES FLOAT NOT NULL;
24. (i)
DDL (Data Definition Language) DML (Data Manipulation Language)
DDL statements are used to create DML statements are used to access and
structure of a table, modify the manipulate data in existing tables which
existing structure of the table and includes inserting data into tables,
remove the existing table. deleting data from the tables, retrieving
data and modifying the existing data.
101
Section 4. 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.
5.- The 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.
102
Check Your Progress :
103
5. What is the use of IS NULL operator ?
Answer : It checks whether the column has null value / no value .
Q2. Write the full forms of DDL and DML . Write any two commands of DML in SQL .
Answer : DDL – Data Definition Language
DML – Data Manipulatiopn Language.
DML commands are INSERT and DELETE.
Q3. 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
Q4. 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
Q5. 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 ;
104
SHORT ANSWER QUESTIONS ( 3 Marks each )
( Each question of query / output of 1 Mark each. )
1. Write SQL Queries for (i) , (ii) and (iii) , 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
c.SELECT DISTINCT CITY FROM STUDENT ;
2. a) Write SQL Queries for (i) , (ii) and (iii) , which are based on the table SHOP
and ACCESSORIES.
i.Display Name and Price of all the Accessories in ascending order of their Price.
ii.Display Id and SName of all Shop located in Nehru Place.
iii.Display Minimum and Maximum Price of each Name of Accessories.
b) Write the outputs based on the SQL Queries (iv), (v) and (vi) based on the table
SHOP and ACCESSORIES (given above).
i)SELECT DISTINCT NAME FROM ACCESSORIES WHERE PRICE> =5000;
ii)SELECT AREA, COUNT(*) FROM SHOP GROUP BY AREA;
iii)SELECT COUNT (DISTINCT AREA) FROM SHOP;
Answer :
a)
i)SELECT Name, Price FROM ACCESSORIES ORDER BY Price Asc;
ii)SELECT ID SName FROM SHOP WHERE Area=”Nehru Place”;
iii)SELECT Name, max (Price), min(Price) FROM ACCESSORIES Group By Name;
b)
i) Name
Mother Board
Hard Disk
LCD
ii) Area Count
CP 2
GK II 1
Nehru Place 2
iii) Count (Distinct AREA )
3
105
Section 5. Update and Delete Commands
1. Update Command:
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
Suppose you have a table called "Students" and want to update the score of a student with a
specific student ID (e.g., 101). You can use the following SQL statement:
UPDATE Students
SET Score = 95
WHERE StudentID = 101;
This query will update the "Score" column for the student with a StudentID of 101 to 95.
2. Delete Command:
Syntax:
Example:
Imagine you have a table called "Orders" and want to delete all orders that were placed before
a certain date (e.g., before January 1, 2023). You can use the following SQL statement:
- In the realm of databases, aggregate functions are essential tools for data summarization and
analysis.
- MAX : Computes the maximum value within a given column.
106
- 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.
Section 9.Equi-Join and Natural Join for Combining Data from Multiple Table
- Equi-Join: This type of join combines tables based on matching values in specified columns
(keys). Equi-joins are the most common type of join in relational databases.
- Natural Join:A natural join combines tables by matching columns with the same name. It
simplifies the process by automatically selecting the common columns without the need to
specify them explicitly.
Q1) 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
Ans – a) DELETE From mytable;
Q2) 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.
Ans – b) Using WHERE clause with Update, only one record can be changed.
Q3) All aggregate functions ignore NULLs except for ________ function.
a. Distinct b.Count(*) c. Average() d. None of these.
Ans- b) Count(*)
Q4) A cartesian product is returned when_______
107
a. A join condition is omitted.
b. A join condition is invalid.
c. All rows in the first table are joined to all rows in the second table.
d. All of these.
Ans- d) All of these
Q5) 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.
Ans- c) Acts like a WHERE clause but is used for groups rather than rows.
Q6) 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.Having, where
b. Group by, having. c.Group, where
Ans- b) Having, where
Q7) _________ joins two or more tables based on a specified column value not equalling a
specified column value
a)Equi join b) Non- equi join c) Outer join d) Natural join
Ans- b) Non-equi join
Q.8)Consider following SQL statement. What type of statement is this? DELETE FROM
employee;
a) DML b) DDL c) DCL d) Integrity constraint
Ans- a) DML
Q.9)Which SQL function is used to count the number of rows in a SQL query?
a) COUNT () b) NUMBER () c) SUM () d) COUNT (*)
Ans- d) COUNT(*)
Q.10) In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and another table,
Beta has degree 3 and cardinality 5, what will be the degree and cardinality of the Cartesian
product of Alpha and Beta?
a. 5,3 b. 8,15 c. 3,5 d. 15,8
Ans b ) 8,15
Q.11)Where and Having clauses can be used interchangeably in SELECT queries?
A. True B. False C. Only in views D. With order by
Ans. B. False
108
Q.12) The SELECT clause _________ is used to collect those rows that have the same value
in a specified column.
Ans. GROUP BY
Q.13) To compare an aggregate value in a condition, ________ clause is used.
Ans. HAVING
Q.14) The SQL built-in function ______ computes the number of rows in a table.
Ans. COUNT
TRUE and FALSE
Q.1 Equi join can use any operator for joining two tables Ans- FALSE
Q.2 The HAVING and WHERE Clauses are interchangeable. Ans- FALSE
Q.3 DELETE FROM table command is same as DROP TABLE command. Ans- FALSE
Q.4 SUM , AVG , MIN and MAX can only be used with numeric columns. Ans- TRUE
Q.5 Conditional updates in table data are possible through UPDATE command. Ans- TRUE
109
Ans. The GROUP BY clause is used to group records of a table on the basis of a common
value of a column and get a summarised result for the group as per a defined function, e.g., if
in a class students belong to different school houses, then we can count the number of students
in each house using a GROUP BY command such as :
SELECT count(house) FROM student
GROUP BY house;
Q.4 Can update command update all the records in one go?
Ans. Yes, UPDATE command will update a table’s all records if we do not specify its
WHERE clause (i.e., no filtering condition)
Q.5 What is a natural join ?
Ans. A NATURAL JOIN is a type of EQUI JOIN with a small difference where common
columns of associated tables are shown once only in the final result set.
3. 13-JAN-1980 12-FEB-2010
4. NAME SALARY
1. Abdul Ahmad 24000
2. Ravi Chander 32000
2- Consider the following tables STORE and SUPPLIERS and answer the following
parts of this question:
TABLE: STORE
ItemNo Item Scode Qty Rate LastBuy
2005 Sharpener Classic 60 8 8 31-Jun-09
2003 Ball Pen 0.25 50 25 25 01-Feb-10
2002 Gel pen premium 120 12 12 24-Feb-10
2006 Gel pen classic 21 250 20 11-Mar-09
2004 Eraser Small 22 220 6 19-Jan-09
2004 Eraser Big 22 110 8 02-Dec-09
2009 Ball Pen 0.5 21 180 18 03-Nov-09
Table : SUPPLIERS
Scode Sname
21 Premium Stationaries
23 Soft Plastics
22 Tetra Supply
Give the output of the following SQL queries:
1. SELECT COUNT (DISTINT Scode) FROM Store ;
2. SELECT Rate * Qty FROM Store WHERE ItemNo= 2004;
3. SELECT Item, Sname FROM Store S, Suppliers P WHERE S.Scode = P.Scode AND
ItemNo = 2006;
4. SELECT MAX (LastBuy) FROM Store ;
Ans.
1. 3
111
2. 880
3. Gel Pen Classic Premium Stationers
4. 24-Feb-10
Table : CLIENT
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
16 Dreams Banglore TP01
Ans.
1. Delhi
Mumbai
Banglore
2. LAK 40 40 1
ABC 55 45 2
XYZ 120 95 2
3. ClientName Manufacturer
Cosmetic Shop ABC
Total Health ABC
Live life XYZ
Pretty Woman XYZ
112
Dreams LAK
Table: CUSTOMER
C_ID CustomerName City I_ID
01 N Roy Delhi LC03
06 H Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Agarwal Banglore PC01
Ans.
1. SELECT * FROM CUSTOMER WHERE City = ‘Delhi’;
2. SELECT * FROM ITEM WHERE PRICE BETWEEN 35000 AND 55000;
3. SELECT CustomerName, City, ItemName, Price FROM CUSTOMER, ITEM
WHERE CUSTOMER.I_ID = ITEM.I_ID;
4. UPDATE ITEM SET Price = Price + 1000;
113
UNIT 8 : 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.
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
114
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)
import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",
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")
115
Check Your Progress :
MCQ
Q-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".
Q-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".
Q-7 Which of the following is not the function of the MYSQL in python ?
A. .connect() B. .close() C. .execute() D. .raw()
Ans.D
116
Q-8 Which keyword we use to fetch the data from the table in database ?
A. fetch B. select C. raw D. All of the above
Ans.B
Mark the correct choice as (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): A database constraint can be added or removed any time from database
tables.
Reasoning(R): Alter table command is used to change the structure of table.
Ans. a
2 Assertion(A): SQL has efficient mechanisms to retrieve data stored in multiple tables in
a MySQL database.
Reasoning(R): The SQL statements CREATE is used to retrieve data from the tables in a
database and is also called query statement.
Ans. c
3. Assertion(A): The resultset refers to a logical set of records that are fetched from the
database by executing an SQL query.
Reason(R): Resultset stored in a cursor object can be extracted by using fetch(...) functions.
Ans. a
117
2. You can check if a database exist by listing all databases in your system by using the
"SHOW DATABASES"(TRUE)
3. You can check if a table exist by listing all tables in your database with the "SHOW
TABLES" statement(TRUE)
4. When creating a table, you MUST create a column with a unique key for each record.
(FALSE)
5. To fill a table in MySQL, use the "INSERT ONTO" statement.(FALSE)
D. SA-1(2 MARKS) -5
1. How can you use Python with MySQL?
ANS. Python can be used with MySQL in a number of ways. One way is to use the mysql-
connector-python library, which is a MySQL driver written in Python. This library can be
used to connect to a MySQL database and perform various operations, such as creating and
executing SQL queries.
E. SA-2(3)
118
1. What is database connectivity?
Ans: Database connectivity refers to connection and communication between an application
and a database system.
2.What is connection? What is its role?
Ans:A Connection (represented through a connection object) is the session between the
application program and the database. To do anything with database, one must have a
connection object.
3.What is a result set?
Ans:A result set refers to a logical set of records that are fetched from the database by
executing a query and made available to the application-program.
4. Which package must be imported in Python to create a database connectivity
application?
Ans:There are multiple packages available through which database connectivity applications
can be created in Python. One such package is mysql.connector.
119
2Q. 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()
120
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.
Example python Code : for connecting a database named ‘mydb’ having user name as ‘User’
, password as ‘password’ , host as ‘localhost’ and database port as 5432
121
2. Which function is used to execute SQL commands in Python's database connectivity?
A. `executeSQL()` B. `runSQL()` C. `execute()` D. `sendSQL()`
Correct Answer: C
3. 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
Correct Answer: A
4. What is the purpose of the `rowcount` attribute in Python's database connectivity?
A. Number of rows affected by the last executed command
B. Total number of rows in the database
C. Total number of columns in the database
D. Number of tables in the database
Correct Answer: A
5. How is dynamic insertion of values achieved in SQL queries?
A. Using `execute()` B. Using `dynamicValues()`
C. Using `%s` format specifier or `format()` D. Using `insertValues()`
Correct Answer: C
6. What does the `commit()` function do in database connectivity?
A. Rolls back the transaction B. Commits the changes made during the transaction
C. Closes the cursor. D. Fetches all rows of the query result
Correct Answer: B
7. Which function retrieves all rows of a query result set in Python's database
connectivity?
A. `fetch()` B. `fetchone()` C. `fetchset()` D. `fetchall()`
Correct Answer: D
8. What is the primary purpose of the `cursor()` function in database connectivity?
A. Connects to the database B. Executes SQL commands
C. Fetches data from the database D. Creates a cursor object to execute SQL queries
Correct Answer: D
9. In Python's database connectivity, what does SQL injection refer to?
A. A way to securely connect to the database
122
B. A method to execute multiple SQL commands in one go
C. A code injection technique where malicious SQL statements are inserted into a query
D. A function to fetch rows from the database
Correct Answer: C
10. Which function is used to close the database connection in Python?
A. `close()` B. `disconnect() C. `end()` D. `finish()`
Correct Answer: A
True/False Questions :
1. The `fetchone()` function retrieves all rows of a query result set. (False )
123
2. The `execute()` function is used for executing SQL commands in Python's database
connectivity. (True)
3. `commit()` function is used to save the changes made during the transaction. (True)
4. SQL injection is a technique to securely connect to the database. (False)
5. The `%s` format specifier or `format()` is used to dynamically insert values into SQL
queries. (True)
124