0% found this document useful (0 votes)
221 views124 pages

XII-Comp. Sc.

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 124

OUR PATRON

Deputy Commissioner
KVS , Regional Office , Kolkata

Honourable Y. Arun Kumar

Guiding Force
Mr. Sanjib Sinha , Assistant Commissioner, KVS Kolkata Region

Mr. C. Vijaya Ratnam, Assistant Commissioner, KVS Kolkata Region

Mr. Dibakara Bhoi, Assistant Commissioner, KVS Kolkata Region

Mr. Amit Baidya , 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 #

01 PYTHON REVISION TOUR 04


02 EXCEPTION HANDLING IN PYTHON 11
03 FUNCTIONS 19
04 DATA FILE HANDLING 27
05 DATA STRUCTURES 42
06 COMPUTER NETWORKS & COMMUNICATION 50
07 DATABASE CONCEPTS & SQL 88
08 MYSQL – PYTHON CONNECTIVITY 112

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.

2. Variables and Data Types:


- Variables:Containers for storing data values. No need to declare data type explicitly.
- Data Types: Include integers, floats, strings, and Booleans.
- Example: num = 10, price = 25.5`, name = "Python", is_valid = True

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).

5. Lists, Tuples, and Dictionaries:


- Lists: Ordered, mutable collections of items. Accessed by index.
- Example: my_list = [1, 2, 3, 4]
- Tuples: Ordered, immutable collections of items.
-Example: my_tuple = (1, 2, 3, 4)
- Dictionaries: Unordered collections of key-value pairs.
- Example: my_dict = {"key": "value", "name": "Python"}
6. Libraries and Modules:
- Libraries: Pre-written code offering ready-to-use functions and classes.
- Modules: Python files containing functions, classes, and variables.
- Importing: Use `import` keyword to include libraries/modules in your code.
- Example: import math or from math import sqrt

Check Your Progress :


Multiple Choice Questions:
1. The numbered position of a letter in a string is called ________.
(a) position (b)integer position (c)index (d)location
Ans. – (c)

2. What datatype is the object below?


L = [1 , 23 , ‘hello’, 1]
(a)list (b)dictionary (c)array (d)tuple
Ans. – (a)

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)

4. What is the value of the following expression?


3+3.00, 3 ** 3.0
5
(a) (6.0, 27.0) (b) (6.0, 9.00) (c) (6, 27) (d) [6.0, 27.0] (e) [6, 27]

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. Which two lines of code are valid string in python ?


(a) This is string (b) ‘This is string’ (c) (This is string) (d) “This is string”
Ans. – (b, d)

7.You have the following code segment :


String1 = “my”
String2 = “work”
Print (string1 + string2)
What is the output of this code
(a) my work (b) work (c) mywork (d) my
Ans. – (c)

8. You have the following code segment :


String1 = “my”
String2 = “work”
Print (string1 + string2.upper())
What is the output of this code

(a) mywork (b) MY Work (c) myWORK (d) My Work


Ans. – (c)

9. Which line of code produces an error?


(a) ”one” + ‘two’ (b) 1+2 (c) ”one” + “2” (d) ‘1’+2
Ans. – (a)

10. Which line of code will cause an error ?


1. num= [5,4,3,[2],1]
2. print (num[0])
3. print (num[3][0])
4. print (num[5])

(a) Line 3 (b) Line 2 (c) Line 4 (d) Line 1


Ans. – (c)

11. Which is the correct form of declaration of dictionary ?


(a) Day = {1: ‘Monday’, 2: ‘Tuesday’, 3: ‘Wednesday’}
(b) Day = {1; ‘Monday’ ,2; ‘Tuesday’, 3; ‘Wednesday’ }

6
(c) Day = [1: ‘Monday’, 2: ‘Tuesday’, 3: ‘Wednesday’]
(d) Day = {1 ‘Monday’, 2 ‘Tuesday’, 3 ‘Wednesday’ }
Ans. – (a)

Assertion - Reasoning Based Questions:

1. Assertion(A) : If the arguments in function called statement match the number


and order of argument as defined in the function definition, such argument are
called positional arguments.
Reasoning(R):During a function called, the argument list first contain default
arguments followed by positional arguments.
Mark the correct choice as :
(a) Both A and R are true and R is the correct explanation of 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.
Ans : (c)

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.

SHORT ANSWER QUESTIONS Consisting 02 Marks each:

Q1. What is the output of the following code fragment?


(i) def increment (n):
n.append([4])
return n
L= [1, 2, 3]
M= increment (L)
print (L, M)
Q2. What is the output of the following code fragment?

def increment (n):


n.append([49])

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’]

Q4. Predict the output of the following code :


fruit = { }
f1 = [‘Apple’, ‘Banana’, ‘apple’ , ‘Banana’]
for index in f1 :
if index in fruit :
fruit [index] += 1
else:
fruit [index] = 1
print (fruit)
print (len(fruit))
Q5. Write the appropriate list method to perform the following task:
(a) Delete a given element from the list.
(b) Delete 3rd element from the list.
(c) Add an element in the end of the list.
(d) Add an element in the beginning of the list.
(e) Add elements of a list in the end of a list.
Q6. What will be the output of the following code snippet:
my_dict = { }
my_dict [(1,2,4)] = 8
my_dict [(4,2,1)] = 10
my_dict [(1,2)] = 12
sum = 0
for k in my_dict:
sum + = my_dict[k]
print (sum)
print (my_dict)
Q7. What are data types ? What are Python’s built-in core data types?
Q8. What are immutable and mutable types? List immutable and mutable types of Pyhton?

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

Introduction to Exception Handling


Exception handling is a crucial aspect of programming, aimed at gracefully managing and
recovering from unexpected errors that can occur during program execution. Errors can range
from simple typos to more complex issues like division by zero or attempting to access a non-
existent file. Python provides a robust mechanism for handling exceptions to prevent program
crashes and improve code reliability.

Handling Exceptions Using Try-Except Blocks


The fundamental construct for handling exceptions in Python is the `try-except` block. It
allows you to define a section of code (the "try" block) where you anticipate exceptions might
occur. If an exception occurs within the "try" block, Python immediately jumps to the
associated "except" block, where you can define how to handle the exception.
Here's the syntax for a basic `try-except` block:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception

- `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.")

Example 2: Handling File Not Found


try:
file = open("non_existent_file.txt", "r") # This may raise a FileNotFoundError
12
except FileNotFoundError:
print("Error: File not found.")
The `finally` Block
In addition to `try` and `except`, you can include a `finally` block. Code within the `finally`
block always executes, regardless of whether an exception was raised or not. It is commonly
used to perform cleanup operations, such as closing files or network connections.

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

Assertion Reason Questions


Choose any one from :
- A. Both assertion and reason are true, and the reason is the correct explanation of the
assertion.
- B. Both assertion and reason are true, but the reason is not the correct explanation of the
assertion.
- C. Assertion is true, but the reason is false.
- D. Assertion is false, but the reason is true.

11. Assertion: Exception handling in programming is primarily used to ignore errors.


Reason: Exceptions can be safely ignored without any impact on program execution.
Answer: C
12. Assertion: The `try` block is optional in a try-except construct.
Reason: You can have an `except` block without a corresponding `try` block.
Answer: D
13. Assertion: The `finally` block is executed only if an exception occurs in the `try` block.
Reason: The `finally` block is used exclusively for handling exceptions.
Answer: B
14. Assertion: In a try-except block, multiple except blocks can be executed simultaneously.
Reason: Multiple exceptions can occur simultaneously in a try-except block.

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)

Short Answer Questions (SA-1)


21. Explain the primary purpose of exception handling in programming.
Answer:Exception handling in programming is primarily used to gracefully manage and
recover from unexpected errors that may occur during program execution. It prevents program
crashes and enhances code reliability.
22. Describe the role of the `try` block in a try-except construct.
Answer: The `try` block in a try-except construct is used to enclose the code that may raise
an exception. It is where the program attempts to execute potentially error-prone code.
23. Why is the `finally` block used in exception handling, and what type of code is typically
placed in it?
Answer: The `finally` block in exception handling is used to specify code that should
execute regardless of whether an exception occurred or not. It is typically used for cleanup
operations, such as closing files or releasing resources.
24. Differentiate between a `try-except` block and a `try-except-finally` block.
Answer: A `try-except` block handles exceptions by catching and handling specific errors
but does not guarantee that certain cleanup operations will be performed. A `try-except-
finally` block, on the other hand, ensures that the code within the `finally` block executes,
making it suitable for cleanup operations.
25. Can you provide an example of when it is appropriate to use multiple `except` blocks
within a single `try` block?

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`.

Short Answer Questions (SA-2)


26. Write a Python code snippet that demonstrates the use of a `try-except` block to handle the
following scenario: Attempting to open a file named "data.txt" and handling the
`FileNotFoundError` by printing an error message.

Answer:
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("Error: File not found.")
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.

UNIT -3 : FUNCTIONS IN PYTHON

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( ).

2. Functions Defined in Modules


Python modules are libraries of code containing functions and variables. You
can use these functions by importing the respective module.
For example, the ‘math` module contains mathematical functions like `sqrt( )`
and `sin( )`.

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.

Creating User-Defined Functions

To create a user-defined function, use the following syntax:


Python Code Syntax
def function_name(parameters):
# Function body
# Code to perform a specific task
return result

Arguments and Parameters


- Parameters: These are placeholders in the function definition. Parameters act as
input variables and are used within the function.
- Arguments:These are the actual values passed to a function when it's called.
Arguments are used to supply data to the function.

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.

Function Returning Values


Functions can return values using the `return` statement. The returned value can be
used in the calling code.

# Code example :
def add(a, b):
return a + b

result = add(3, 4) # result will be 7

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

Check Your Progress :


Multiple Choice Questions (MCQ)
1. Which type of function is the `print()` function in Python?
A. Built-in function B. User-defined function

21
C. Module function D. None of the above
Answer: A

2. What is the primary purpose of user-defined functions in Python?


A. Enhance code readability B. Reduce code complexity
C. Promote code reusability D. All of the above
Answer: D
3. Which keyword is used to define a function in Python?
A. define B. function
C. def D. define_function
Answer: C
4. What is the role of parameters in a function?
A. They store the function's return value.
B. They hold data that can be accessed from outside the function.
C. They act as placeholders for input values.
D. They determine the function's name.
Answer: C
5. Which of the following is an example of a default parameter in a function?
A. def greet(name="Guest") B. def greet(name)
C. def greet(name, default="Guest") D. def greet()
Answer: A
6. When using positional parameters in a function, how are arguments matched to parameters?
A. Based on alphabetical order B. Based on their names
C. Based on their positions D. Randomly
Answer: C
7. What keyword is used to return a value from a function?
A. return B. value
C. result D. yield
Answer: A
8. In Python, what happens when a function is called?

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

Assertion Reason Questions


Choose any one from :
A. Both assertion and reason are true, and the reason is the correct explanation of the
assertion.
B. Both assertion and reason are true, but the reason is not the correct explanation of the
assertion.
C. Assertion is true, but the reason is false.
D. Assertion is false, but the reason is true.
11. Assertion: User-defined functions enhance code reusability.
Reason: They allow you to define your own keywords in Python.
Answer: A
12. Assertion: Default parameters in Python functions are mandatory.
Reason: Default parameters are automatically provided when you call a function.
Answer: B
13. Assertion: Variables defined inside a function can be accessed from outside that function.
Reason: Local variables have module-level scope.
Answer: C
14. Assertion: Python's `print()` function is a user-defined function.

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)

Short Answer Questions (SA-1)


21. Explain the role of parameters in a Python function.
Answer:Parameters are placeholders in a function's definition used to receive input data.
They allow functions to work with different values each time they are called.
22. Provide an example of a user-defined function with default parameters and explain its use.
Answer: `def greet(name="Guest"):` is an example. It greets a person by name, defaulting to
"Guest" if no name is provided.
23. How does Python match arguments to positional parameters in a function?
Answer: Python matches arguments to positional parameters based on their order of
appearance. The first argument corresponds to the first parameter, the second to the second,
and so on.
24. What is the purpose of the `return` statement in a Python function?
Answer: The `return` statement is used to send a value back from a function to the calling
code. It is used to return the result of a computation or an operation.
25. Explain the concept of variable scope in Python, specifically the difference between global
and local scope.

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

scores = [85, 90, 78, 92, 88]


class_average = calculate_average(scores)
print(f"The average test score is {class_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

def remove_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)

print(f"Total books across all branches: {total_books}")


print(f"Branch 1 books: {branch1_books}")
print(f"Branch 2 books: {branch2_books}")
print(f"Branch 1 books after removal: {branch1_books - branch1_books_removed}")
In this case, the global variable `total_books` keeps track of the total number of books in all
branches, while local variables within each branch's functions (e.g., `branch_books`) keep
track of the number of books at each branch. This allows you to manage the library's inventory
effectively.

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.

Why the Files are used?


• The data stored with in a file is known as persistent data because this data is
permanently stored in the system.
• Python provides reading and writing capability of data files.
• We save the data in the files for further use.
• As you save your data in files using word, excel etc. same thing we
• can do with python.
• “A File is a collection of characters in which we can perform readand write
functions. And also we can save it in secondary storage.”

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>)

File accessing modes


> read( r ) : To read a file
> write(w) : To write into a file
> append( a) : To write at the end of the file
Mode Description

r To read the file which is already existing.

rb Read Only in binary format.


r+ To Read and write but the file pointer will be at the beginning of the file.

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.

Opening a File Using the `with` Clause


In Python, file handling is a fundamental aspect of programming. You can work with files for
various purposes, such as reading data, writing data, and appending to existing files. A
common practice when working with files is to use the `with` clause, which simplifies file
handling by automatically managing resources and ensuring that the file is properly closed
when you are done with it.

Here's how to open a file using the `with` clause:


Syntax :
with open("filename.txt", "mode") as file:
# Code to work with the file
- `"filename.txt"` is the name of the file you want to open.
- `"mode"` specifies the mode in which you want to open the file, such as `"r"` for reading,
`"w"` for writing, or `"a"` for appending.

Writing and Appending Data to a Text File


a) Writing Data to a File
To write data to a text file, you can use the `write()` method. It allows you to write a single
string to the file. If the file doesn't exist, it will be created. If it does exist, the previous content
will be overwritten.
Example Code :

30
with open("example.txt", "w") as file:
file.write("This is a line of text.\n")

b) Appending Data to a File


To append data to an existing text file, you can use the `write()` method in append mode
(`"a"`). This will add the new data to the end of the file without overwriting the existing
content.
Example Code :
with open("example.txt", "a") as file:
file.write("This is another line of text.\n")

Reading from a Text File


a) Reading the Entire File
To read the entire contents of a text file, you can use the `read()` method. It returns the file's
content as a string.
Code Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
b) Reading a Single Line
To read a single line from a text file, you can use the `readline()` method. It reads and returns
a single line from the file.
Example Code :
with open("example.txt", "r") as file:
line = file.readline()
print(line)
c) Reading All Lines
To read all lines of a text file into a list, you can use the `readlines()` method. Each line is
stored as an element in the list.
Example Code :
with open("example.txt", "r") as file:
lines = file.readlines()

31
for line in lines:
print(line)

Seek and Tell Methods


- The `seek()` method is used to move the file's cursor to a specified position within the file.
This is helpful when you want to read or write data from a specific location.
Example Code :
with open("example.txt", "r") as file:
file.seek(5) # Move to the 6th character
content = file.read()
print(content)
- The `tell()` method is used to determine the current position of the file's cursor. It returns the
current file pointer's position.
Example Code
with open("example.txt", "r") as file:
file.read(10) # Read the first 10 characters
position = file.tell()
print("Current position:", position)

Binary File Handling

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.

The tell() Function


The tell() method of python tells us the current position within the file.

The seek() Function


The seek(offset, from) method changes the current file position. 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

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()

The Pickle Module :

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.

Serialization is the process of transforming data or an object in memory (RAM) to a stream of


bytes called byte streams. These byte streams in a binary file can then be stored in a disk or in
a database or sent through a network. Serialization process is also called pickling.
De-serialization or unpickling is the inverse of pickling process where a byte stream is
converted back to Python object.

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.

The dump() method:

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).

Syntax of dump() is as follows:


dump(data_object, file_object)

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.

#Pickling data in Python


import pickle
listvalues=[1,"Geetika",'F', 26]
fi leobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fi leobject)
fileobject.close()

The load() method

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().

#Unpickling data in Python


import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)

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 b. Binary file

2. The command for opening a file in Python file handling is ____________.


a. open() b. update() c. both a) and b) d. None of the above

Answer a. open()

3. The command for closing a file in Python file handling is ____________.

a. close() b. closing() c. object() d. None of the above

Answer ⟵ a. close()

4. _________ text file mode is used to read data from file.

a. ‘r’ b. ‘rb’ c. ‘r+’ d. None of the above

Answer a. ‘r’

5. _________ text file mode is used to append data in the file using file handling.

a. ‘w’ b. ‘ab’ c. ‘a’ d. None of the above

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+

7. Which of the following is not true about binary files?

a) Binary files are store in terms of bytes


b) When you open binary file in text editor will show garbage values
c) Binary files represent ASCII value of characters
d) All of the above
Ans: c) Binary files represent ASCII value of characters

8. What is the difference between wb and wb+ mode?

a) wb mode is used to open binary file in write mode and wb+ mode open binary file both for
read and write operation.
b) In wb mode file open in write mode and wb+ in read mode

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.

9. The pickle module in Python is used for:

a) Serializing any Python object structure b) De-serializing Python object structure


c) Both a and b d) None of these
Ans: c) Both a and b
10. Which method is used to convert Python objects for writing data in binary file?

a) write() b) load() c) store() d) dump()

Ans: d) dump()

11. seek() function is used for _______.

a) positions the file object at the specified location.

b) It returns the current position of the file object

c) It writes the data in binary file

d) None of these

Ans: a) positions the file object at the specified location.

12. Which is not the valid mode for binary files?

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?

a) read() b) open() c) dump() d) load()

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.

a) seek() b) load() c) position() d) tell()


Ans: d) tell()

(ASSERTION AND REASONING based questions)

Mark the correct choice as:

i. Both A and R are true and R is the correct explanation for A

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

2. Assertion(A): an open file can be close using close() function.

Reason(R): sometimes the data written onto files is held in memory until the file is closed.

Ans: 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.

Reason(R): Pickle.load() function is used to retrieve pickled data.

Ans: ii. Both A and R are true but R is not the correct explanation for A

4. Assertion(A): The seek(offset,from) method changes the current file position.

Reason(R): If from is 0, the beginning of the file to seek. If it is set to 1, the current position
is used. If it is set to 2 then the end of the file would be taken as seek position. The offset
argument indicates the number of bytes to be moved.

Ans: 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.

Ans: iii. A is True but R is False

(TRUE/FALSE Questions)

1. Pickling is a process by which a Python object is converted to a byte stream.


Ans: True
2. The load() function of the pickle module performs pickling.
Ans: False
3. The dump() function of the pickle module performs unpickling.
Ans: False
4. When you open a file for writing, if the file does not exist, a new file is created.
Ans: True
5. When you open a file for appending, if the file exists, the existing file is overwritten with the new
file.

Ans: False

Short Answer Type Questions ( 2-Marks Questions )

1. Identify the error in the following code:


import pickle
data=[‘one’, 2, [3, 4, 5]]
with open(‘data2.dat’, ‘rb’) as f:
pickle.dump(data, f)
Ans: The file is opened in read mode and dump() function tries to write onto file, hence there
is error line 3.
Correct code : with open(‘data2.dat’, ‘wb’) as f:
2. Any recipe uses some ingredients. Write a program to store the list of ingredients in a
binary file recipe.dat .
Ans: import pickle
ingredients= [‘cucumber’, ‘pumpkin’, ‘carrot’, ‘peas’]
with open(‘recipe.dat’, ‘wb’) as fout:
pickle.dump(ingredient, fout)
3. A binary file “student.dat” has structure [rollno, name, marks]. Write a user defined
function insertRec() to input data for a student and add to student.dat.
Ans:
import pickle
def insertRec():
f=open(‘student.dat’,’ab’)
rollno = int (input(‘Enter Roll Number :’))
name=input("Enter Name :")
marks = int(input(‘Enter Marks :’))
rec = [rollno, name, marks ]
38
pickle.dump( rec, f )
f.close()
4. Considering the following definition of dictionary MULTIPLEX, write a method in
python to search and display all the content in a pickled file CINEMA.DAT, where
MTYPE key of the dictionary is matching with the value ‘Comedy’.
MULTIPLEX = {‘MNO’ : ____, ‘MNAME’:_____, ‘MTYPE’:______}
Ans:
import pickle
def search():
file=open('CINEMA.DAT', 'rb')
try:
while True:
MULTIPLEX=pickle.load(file)
if(MULTIPLEX['MTYPE']=='Comedy'):
print(MULTIPLEX)
except EOFError:
f.close()
5. What will be the output of following code:
import pickle
names=['First', 'Second', 'Third', 'Fourth', 'Fifth']
lst=[ ]
for i in range(-1, -5, -1):
lst.append(names[i])
fout= open('test.dat', 'wb')
pickle.dump(lst, fout)
fout.close()
fin= open('test.dat', 'rb')
nlist=pickle.load(fin)
fin.close()
print(nlist)
Ans: ['Fifth', 'Fourth', 'Third', 'Second']

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()

Case Study Based Question-1

Ramesh loves programming. He joined an institute for learning. He is learning python. He


learned all the python concepts like strings, lists, tuple, dictionaries etc. but he wants to learn
file handling in python. He is trying to learn binary file handling. His teacher gave him partial
code to write and read data from employee.dat having structure empno, name, salary. Help
Ramesh to complete the code:

___________________ # 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.

a) csv b) random c) pickle d) file

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)

c) pickle.load(dict,fr) d) none of these

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

(i). Help Abhay to complete the Statement1.


Ans: f = open('bank.dat','wb')
(ii). How will he write the record in Statement2?
Ans: rec = [acc_no, cust_name, bal]
(iii). What code will be there in Statement3 to write record in file?
Ans: pickle.dump(rec, f)
(iv). Complete the Statement4 to open the file with correct mode.
Ans: f = open('bank.dat','rb')
(v). What will be the Statement5?
Ans: rec = pickle.load(f)

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

Push (Add/Insert): Adding an element in stack is called Push operation.


When the stack is empty, the value of top is Basically, an empty stack is initialized with an invalid
subscript. Whenever a Push operation is performed, the top is incremented by one and then the new
value is inserted on the top of the list till the time the value of top is less than or equal to the size of the
stack.
The algorithm for Push operation on a stack:
1. Start 2. Initialize top with -1 3. Input the new element
4. Increment top by one. 5. Stack[top]=new element. 6. Print “Item inserted” 7. Stop

Pop (Removing (deleting) an element from the stack.


Removing existing elements from the stack list is called pop operation. Here we must check if the stack
is empty by checking the value of top. If the value of top is -1, then the stack is empty and such a
situation is called Underflow. Otherwise, Pop operation can be performed in the stack. The top is
decremented by one if an element is deleted from the list. The algorithm for pop operation is as follows:
1. Start. 2. If the value of top is -1 go to step 3 else go to step 4
3.Print “Stack Empty” and go to step 7 4. Deleted item =Stack[top]
44
5. Decrement top by 1 6. Print “Item Deleted”. 7. Stop
Traversal in a stack: Traversal is moving through the elements of the stack. If you want to display all
the elements of the stack, the algorithm will be as follows:
1. Start 2. Check the value of top. If top=-1 go to step 3else go to step 4
3.Print “Stack is Empty” and go to step7 4. Print the top element of the stack
5. Decrement top by 1 6. If top=-1 go to step 7 else go to step 4 7. Stop

Stack implementation using list with function definition


import sys
def Push(stack):
N=int(input("enter no of record you want to ADD"))
for i in range(N):
data=input("enter name")
stack.append(data)
def Pop(stack):
if(stack==[]):
print("stack is empty")
else:
N=int(input("enter no of record you want to DELETE"))
for i in range(N):
print("elements to be deleted",stack.pop())
def display(stack):
if(stack==[]):
print("no element for deletion")
else:
top=len(stack)-1
for i in range(top,-1,-1):
print(stack[i])
s=[]

#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? ")

Check Your Progress :

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')

UNIT -6 : COMPUTER NETWORK AND COMMUNICATIONS


A system of interconnected computers and computerized peripherals such as printers is called
computer network. This interconnection among computers facilitates information sharing
among them. Computers may connect to each other by either wired or wireless media.

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

ARPANET, in full Advanced Research Projects Agency Network, experimental computer


network that was the forerunner of the Internet.

NSFNET: in full National Science Foundation Network, used between 1985 to 1995 to

51
promote advanced research and education

INTERNET : it is the global network of computing devices including desktop, laptop,


servers, tablets, mobile phones, other handheld devices as well as peripheral devices such as
printers, scanners, etc.
▪ also consists of networking devices such as routers, switches, gateways, etc.
▪ The Internet provides a capability so powerful and general that it can be used for almost any
purpose that depends on information, and it is accessible by every individual who connects to
one of its associated networks.

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)

B] Data Communication Terminologies

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.

Components of data communication: Five most important components are sender,


receiver, communication medium, the message to be communicated, and certain rules called
protocols to be followed during communication. The communication media is also called
transmission media. Below figure shows the role of these five components in data
communication.

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

The five main components of data communication are as follows:


SENDER: Sender is a device which is capable of sending data over a communication
network. In data communication Sender is also called Source.
RECEIVER: Receiver is a device which is capable of receiving data over a communication
network. In data communication Receiver is also called Destination.
MESSAGE: message is the information being exchanged between a sender and a receiver
over a communication network.
6] COMMUNICATION MEDIUM: Communication medium is the path or channel through
which the information is moved from the sender to the receiver. A communication
medium can be either wired/guided or wireless/unguided.

7] MEASURING CAPACITY OF COMMUNICATION MEDIA


Capacity of a communication channel means the maximum quantity of signals that a
communication channel can carry.
The capacity of a communication medium is measured by :
a. bandwidth and
b. data transfer rate.
BANDWIDTH
Bandwidth is the difference between the highest and lowest frequencies (measured in Htz) a
transmission media can carry. It is also the maximum capacity of a wired or wireless
communications link to transmit data over a network connection in a given amount of time.
Generally speaking, the higher the bandwidth, the quicker your devices download information
from the internet.
8] DATA TRANSFER RATES
Data transfer rate is the number of bits transmitted through a channel per unit of time.
Data transfer rate is measured in bits per second (bps).
It is also measured in Kilobits per second (Kbps),

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

10] SWITCHING TECHNIQUES


In large networks, there may be more than one paths for transmitting data from sender to
receiver. The process of selecting a path of data out of the available paths is called switching.

There are two popular switching techniques –


• circuit switching and
• packet switching.
1. Circuit Switching
In circuit switching, whenever a source end node wants to send a message to the destination end
node a physical link is first established between the source and the destination. Then only
the data transmission takes place. After the complete transmission of data this physical link is
terminated.
Simple example of a circuit switching is telephone network in which a person calls another
person. When the call receiving person receives the call, then only the connection is established.
Then the message is conveyed and finally the connection is terminated.

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.

Types of Transmission Media:


In data communication terminology, a transmission medium is a physical path between the
transmitter and the receiver i.e. it is the channel through which data is sent from one place to
another.

Transmission Media is broadly classified into the following types:


a-Wired Communication Media (Guided Media): 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.
Features:
• High Speed
• Secure
• Used for comparatively shorter distances

b- Wireless Communication Media (Unguided media): By means of waves. Examples: Infrared,


Radiowave, Microwave and Satellite.

Wired Communication Media (Guided Media):

There are 3 major types of Wired Media (Guided Media):

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.

Wireless Communication Media (Unguided media):


• In wireless communication technology, information travels in the form of
electromagnetic signals through air.
• Electromagnetic spectrum of frequency ranging from 3 KHz to 900 THz is available for
wireless communication.
• Wireless technologies allow communication between two or more devices in short to
long distance without requiring any physical media.
There are many types of wireless communication technologies such as Bluetooth, WiFi, WiMax
etc.

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.

Classification of transmission waves and their properties


Transmission Properties
Waves
Radio Waves 1. Waves of frequency range 3 KHz - 1 GHz
2. Omni-directional, these waves can move in all directions
3. Radio waves of frequency 300KHz-30MHz can travel long distance
4. Susceptible to interference
5. Radio waves of frequency 3-300KHz can penetrate walls 6. These
waves are used in AM and FM radio, television, cordless phones.
Microwaves 1. Electromagnetic waves of frequency range 1GHz - 300GHz.
2. Unidirectional, can move in only one direction.
3. Cannot penetrate solid objects such as walls, hills or mountains.
4. Needs line-of-sight propagation i.e. both communicating antenna must
be in the direction of each other.
5. Used in point-to-point communication or unicast communication such
as radar and satellite.
6. Provide very large information-carrying capacity.

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.

11] Network Devices :

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.

3. RJ45 Connector: Registered Jack 45 connector, Used to connect Ethernet cables to


devices such as computers, switches, and routers, Ensures a secure and reliable physical
connection.

4. Repeater: Amplifies and retransmits signals in a network, Extends the range of


network signals, especially in large or congested environments.

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

12] Computer Network :


A Computer Network is a group of two or more interconnected computer systems that use
common connection protocols for sharing various resources and files.
Different Types of Computer Networks
The classification of network in computers can be done according to their size as well as their
purpose.

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:

• It is mostly personal devices network equipped within a limited area.


• Allows you to handle the interconnection of IT devices at the surrounding of a single
user.
• PAN includes mobile devices, tablet, and laptop.
• It can be wirelessly connected to the internet called WPAN.
• Appliances use for PAN: cordless mice, keyboards, and Bluetooth systems.

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:

• It is a private network, so an outside regulatory body never controls it.


• LAN operates at a relatively higher speed compared to other WAN systems.
• There are various kinds of media access control methods like token ring and ethernet.

A Metropolitan Area Network or MAN is consisting of a computer network across an entire


city, college campus, or a small region. This type of network is large than a LAN, which is
mostly limited to a single building or site. Depending upon the type of configuration, this type
of network allows you to cover an area from several miles to tens of miles.

Features of MAN:-

59
Here are important characteristics of the MAN network:

• It mostly covers towns and cities in a maximum 50 km range


• Mostly used medium is optical fibers, cables
• Data rates adequate for distributed computing applications.

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.

13] NETWORK TOPOLOGIES


Network topologies refer to the physical or logical arrangement of nodes and connections in a
computer network. Each type of topology has its own set of advantages and disadvantages,
which can significantly impact the network's performance, scalability, and fault tolerance.
Here's a comparison of the working, advantages, and disadvantages of common network
topologies:

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.

6. Tree (Hierarchical) Topology:


- Working: Tree topology combines elements of star and bus topologies, creating a hierarchy
of central hubs connected by branch lines.
- Advantages: Scalable and suitable for large networks,Logical organization with centralized
control.
- Disadvantages: Dependency on the central hubs,Failure of a central hub can disrupt a portion
of the network.

10] NETWORK PROTOCOL S:


Network protocols are a set of rules outlining how connected devices communicate across a
network to exchange information easily and safely. Protocols serve as a common language for
devices to enable communication irrespective of differences in software, hardware, or internal
processes.

TYPES OF NETWORK PROTOCOL

There are various types of network protocols that support a major and compassionate role in
communicating with different devices across the network.

i) TCP - Transmission Control protocol ii)HTTP - HyperText Transfer Protocol


iii)SMTP - Simple Mail Transfer Protocol iv)FTP - File Transfer Protocol
v)POP - Post office protocol vi)UDP - User Datagram protocol
vii)PPP - Point to point protocol viii)HTTPS- Hypertext transfer protocol Secure
ix)VoIP- Voice over Internet protocol x)Telnet

BRIEF NOTES ON TYPES OF NETWORK PROTOCOLS :

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:

1. Internet Protocol (IP):


- Role: IP is responsible for addressing and routing data packets across the Internet or any
network using the TCP/IP protocol suite. It ensures data reaches its intended destination by
assigning unique IP addresses to devices.

2. Transmission Control Protocol (TCP):


- Role: TCP provides reliable, connection-oriented data transfer. It establishes and manages
connections, handles data segmentation, and ensures data integrity through error checking and
retransmission.

3. User Datagram Protocol (UDP):


- Role: UDP is a connectionless protocol that allows quick, low-overhead data transmission.
It's used for real-time applications like video streaming and VoIP where occasional data loss is
acceptable.

4. Hypertext Transfer Protocol (HTTP):


- Role: HTTP is the foundation of the World Wide Web. It defines how web browsers and
servers communicate, enabling the retrieval and display of web content such as text, images,
and multimedia.

5. File Transfer Protocol (FTP):


- Role: FTP is used for transferring files between a client and a server. It manages the upload
and download of files, making it a fundamental protocol for sharing data on the Internet.

6. Simple Mail Transfer Protocol (SMTP):


- Role: SMTP is used for sending and relaying email messages. It ensures the reliable delivery
of emails by routing messages between mail servers.

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.

8. Dynamic Host Configuration Protocol (DHCP):


- Role: DHCP automates the assignment of IP addresses and network configuration to devices
in a local network. It simplifies network administration by dynamically allocating addresses.

9. Domain Name System (DNS):


- Role: DNS translates human-readable domain names (e.g., www.example.com) into IP
addresses, allowing users to access websites and services without remembering numerical IP
addresses.

10. Secure Sockets Layer (SSL) / Transport Layer Security (TLS):


- Role: SSL/TLS protocols provide secure, encrypted communication over the internet. They
are used for protecting sensitive data during online transactions, such as online banking and e-
commerce.

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.

12. HTTPS (Hypertext Transfer Protocol Secure):


- Role: HTTPS is a secure version of HTTP, primarily used for secure communication on the
World Wide Web. It ensures data privacy and integrity during data transmission between a web
browser and a web server.

13. Telnet (Telecommunication Network):


- Role: Telnet is a network protocol used for remotely accessing and controlling devices or
computers over a network. It enables users to log in to a remote host and perform various tasks,
but it lacks security measures.

14. VoIP (Voice over Internet Protocol):


- Role: VoIP is a technology that allows voice and multimedia communication over the Internet
and other IP-based networks. It transforms analog voice signals into digital data packets for
transmission, making it an efficient and cost-effective means of voice communication. Eg.
Skype and Zoom, uses VoIP

4. PPP(Point to Point Protocol)


PPP is a communication protocol of the data link layer that is used to transmit multiprotocol
data between two directly connected (point-to-point) computers.

11] Introduction to Web Services:

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:

World Wide Web (WWW):


• The World Wide Web, commonly known as the Web, is a global system of
interconnected hypertext documents and multimedia content.
• It is accessed via the internet using web browsers and allows users to navigate and
interact with web pages.
Hyper Text Markup Language (HTML):
• HTML is the standard markup language used to create web pages.
• It defines the structure and content of web documents, using tags to format text, embed
images, create links, and more.
Extensible Markup Language (XML):
• XML is a versatile markup language designed for data exchange and representation.
• It is used to structure and store data in a format that is both human-readable and machine-
readable.

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.

Check your Progress :

MCQ Questions

1. ARPANET stands for-


(a) Advanced Real Projects Air Network
(b) Advanced Research Preparation Agency Network
(c) Advanced Recruitment Process Agency Network
(d) Advanced Research Projects Agency Network

2. In 1990s, the internetworking of which three networks resulted into Internet?


(a) WWW, GPS and other private networks
(b) ARPANET, NSFnet and other private networks
(c) ARPANET, NSFnet and other public networks
(d) ARPANET, GPS and NSFnet

3. The combination of two or more interconnected networks is called

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?

A) Computer Network B) Intranet


C) Internet D) All of the above

10. At first, ARPANET was intended to support the ……………… on fault-tolerant


computernetworks.

A) Military research B) Educational research


C) Governmental research D) Scientific research

11.With the use of computer network, we can share:


(a) Data (b) Resources

(c) Both of the above (d) None of the above

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

23. Which of the following is/are not communication media?


a. Microwave b. Optical Fiber cable
c. Node d. Radio wave

24. The ____________ is over which the messages are sent.


a. Signal b. Channel
c. Protocol d. Sender

25. The other name for communication medium is:


a. Channel b. Source
c. Hub d. Switch

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

27. In data communications, transmission medium is the path established between


____________?
a. Sender and Receiver b. Source and Destination
c. Server and Client d. All Mentioned Above

28. In _____________network, bits are transmitted as pulses of light?


a. Fibre Based Network b. Copper Based Network
c. Radio-waves Based Network d. All Mentioned Above

29. Transmission Media is classified as ____________?


a. Unguided b. Guided
c. Direct d. a & b both

30. Physical medium to transmit signals is present in _____________?


a. Unguided b. Guided
c. Direct d. Indirect

31. What are the various types of twisted pairs?


a. Shielded Twisted Pair b. Un- Shielded Twisted Pair
c. Coaxial Cable d. a & b both

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

42. Which type of network consists of both LANs and MANs?


a. Wide Area Network b.Local Area Network
c.Both i) and ii) d.None of the above

43. Physical or Logical arrangement of network is called


a)Networking b)Topology
c)Routing d)Control

44. A Computer network is__________ connected together.


a)one computer b)two or more computer
c)three or more computer d)four or more computers

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

47. Identify the protocol primarily used for browsing data.


(A)FTP (B)TCP (C) SMTP (D)HTTP

48. HTTP refers to ?


(A)Hyper text transmission protocol (B)Hyper text transfer protocol
(C)Hyper text tie protocol (D) None of these

49. POP3 is a protocol used for ______


(A)Reading protocols (B)Acessing emails
68
(C)Downloading images from the server (D)Downloading emails

50. Which protocol holds the email until you actually delete it?
(A)POP3 (B)IMAP (C)SMTP (D) FTP

51. SMTP is used for


(A)Adding address to emails. (B)Connecting with server
(C)Sending emails from one server to another. (D)Downloading emails

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

55. What does WWW stand for?


A) World Web Web B) Web World Wide
C) World Wide Web D) Wide World Web

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

58. What is the primary function of a domain name?


A) To specify the web server's IP address B) To define the path to a web page
C) To store web content D) To serve as a web browser
59. What part of a URL typically follows the domain name and identifies the specific
resource on a website?
A) Protocol B) Port C) Query string D) Path

60.What is a website composed of?


A) Web browsers only B) Web servers only
C) Web browsers and web servers D) Domain names only

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

63. What service does a web hosting provider offer?


A) Domain registration B) Creating web content
C) Storing and serving web content D) Web browsing

64. Which of the following components is NOT part of a URL?


A) Protocol B) Domain name C) Port number D) File extension

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

One marks Questions

1) ARPANET stands for ____________________.


2) Give any two advantages of computer network.
3) Give any two disadvantages of computer network.
4) NFSNET stands for _____________________.

Answers :

One Marks questions:


1) Advanced Research Project Agency Network
2) Resource sharing, Reliability of data or any related it.
3) Cost of setup, Threat to Data Security or any related it.
4) National Science Foundation Network

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. Expand the following :


2. Kbps
3. Mbps
4. Gbps
5. Bps
Ans: Kilobits per second , Megabits per second , Gigabits per second , bits per second.

Two Marks Questions ( SA Type )


1. What is Data Communication and Characteristics of Data Communication?
Ans. Data communications means the exchange of data between two devices via some
form of transmission medium such as a wire cable.

For data communications to occur, the communicating devices must be part of a


communication system made up of a combination of hardware (physical equipment)
and software (programs).

Characteristics of Data Communications:

The effectiveness of a data communications system depends on four fundamental


characteristics: delivery, accuracy, timeliness, and jitter.

1. Delivery , 2. Accuracy , 3. Timeliness , 4. Jitter

Q2. Write any one difference between circuit switching and packet switching .

Circuit Switching Packet Switching


A dedicated path is established between No dedicated path but message are sent in
sender a receiver chunk of bytes ,in smaller packets .

Q4. Explain the term IP address with a suitable example.

Ans: IP address or Internet Protocol address is a unique logical 4byte address . Example:

71
192.168.1.190

Q5. Write any two disadvantages of Circuit switching .

Ans: 1. Time required to setup a physical connection between the sender and the receiver

makes delay in communication

2. Since a communication channel is dedicated for a particular transmission, it cannot be

utilized for other communication, even if the channel is free.

Q6. Write True or False


a.Unguided media refers to wireless communication channels.
Answer: True.
b. The coaxial cables are best fitted in LANs
Answer: False
c. The twisted-pair cables provide high-speed data transmission compared to other cables.
Answer: False.
d, Bluetooth cannot penetrate the walls.
Answer: False
e.Optical networks can transmit voice, data, and video.
Answer: True.
f. Bus Topology is cost effective.True or False.
Answer True
g. LAN is made only with wired connection.True or False.

Answer : False

h. WAN and Internet are two different concept.True or False.


Answer : True

ASSERTION & REASONING QUESTIONS:

1. 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

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.

2.Mark the correct choice as


a.Both statements are correct.
b. Both statements are incorrect.
c.Statement 1 is correct, but Statement 2 is incorrect
d.Statement 1 is incorrect, but Statement 2 is correct

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.

SA-1 (2 MARKS QUESTION)

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).

Q6) i. What is the full form of MODEM?


ii.What is the full form of Wifi?
ANS- i.MODULATOR -DEMODULATOR, ii- Wireless Fidelity
Q7) Why is switch called an intelligent hub?

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

Q9) What is the difference between a Hub and Switch?


ANS-
SN Hub Switch
1 It broadcast signals to all the devices it sends signals to only selected devices
connected instead of sending to all
2 It is not an intelligent device it is an intelligent device.
3 Hub is simply old type of device and switch is very sophisticated device and
is not generally used. widely used.

Q10) Write two characteristics of Wi-Fi.


Ans
(a) It allows an electronic device to exchange data or connect to the internet wirelessly using
microwaves.
(b) Network range of Wi-Fi is much less than other network technologies like wired LAN.

Q11)What is HTTPs and what port does it use?


Answer: HTTPs is a Secure HTTP. HTTPs is used for secure communication over a computer
network. HTTPs provides authentication of websites that prevents unwanted attacks.
In bi-directional communication, the HTTPs protocol encrypts the communication so that the
tampering of the data gets avoided. With the help of an SSL certificate, it verifies if the requested
server connection is a valid connection or not. HTTPs use TCP with port 443.

Q12)List the similarities between UDP and TCP.

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.

Q14)Expand the following : SMTP,PPP


Answer: SMTP-Simple Mail Transfer Protocol
PPP- Point to point protocol

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).

Q16) What does WWW stand for?


Answer: World Wide Web.
Q17) What is HTML used for?
Answer: HTML is used for structuring and formatting web content.
Q18) What does XML stand for, and what is its primary purpose?
Answer: XML stands for Extensible Markup Language. Its primary purpose is to structure and
encode data in a machine-readable format.
Q19) What is a domain name?
Answer: A domain name is a human-readable web address that helps locate resources on the
internet.
Q20) What does URL stand for, and what is its role?
Answer: URL stands for Uniform Resource Locator. It is used to specify the address of a
resource on the internet.
Q21) What is the main function of a web browser?

77
Answer: The main function of a web browser is to display web content and allow users to
interact with it.

SA-2(3 MARKS)-3 QUESTIONS


Q1. What is modem? Define the functioning of internal modem and external modem.
ANS-
Modem stands for modulator de-modulator that converts analog signals to digital signals at the
sender's end. It converts digital signals back to analog signals at the receiver's end.
• The two types of modems are: internal modem and external modem.
Functioning of internal modem: - The modems that are fixed within the computer.
Functioning of external modem: - The modems that are connected externally to a computer as
other peripherals are connected.

Q2- What do you mean by a gateway? Why it is used in network?


ANS- Gateway” as the name suggests, it acts as a “gate” between an organisation's network (say
LAN) and the outside world of the Internet(i.e WAN). If a node from one network wants to
communicate with a node of a foreign network, it will pass the data packet to the gateway, which
then routes it to the destination using the best possible route. For simple Internet connectivity at
homes, the gateway is usually the Internet Service Provider(ISP) that provides access to the
entire Internet.

Q3- What are Wi-Fi cards? Explain.


ANS- A Wi-Fi card is either an internal or external Local Area Network adapter with a built-
in wireless radio and antenna. The most common Wi-Fi cards used in desktop computers are
PCI-Express Wi-Fi cards made to fit the PCI-Express card slots on the motherboard.

Q4)Write a short note on functioning of telnet?

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.

Q5)Write short Notes on a)POP3 b)SMTP

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

Q8)Compare between HTTP and HTTPS


Answer :The only difference between the two protocols is that HTTPS uses TLS (SSL) to
encrypt normal HTTP requests and responses, and to digitally sign those requests and responses.
As a result, HTTPS is far more secure than HTTP.

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.

CASE BASED QUESTIONS


Q1) RCI is an online corporate training provider company for IT related courses. The
company is setting up their new campus in Kolkata. You as a network expert have to study
the physical locations of various blocks and the number of computers to be installed. In
the planning phase, provide the best possible answers for the queries (i) to (iii) raised by
them.

Block to Block Distances (in mtrs.)

Expected computers to be installed in each block

(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

Distances between various buildings are as follows:

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.

Answer. (i) Research Lab: As it has the maximum number of computers


(ii) (a) Repeater will be placed between Accounts to Packing Unit as the distance is more
than 100 mtrs.
(b) Hub/Switch will be placed in each block
(iii) Ethernet Cable

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

ANS- Modem or Switch or 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:

Law School to Business School 60 m


Law School to Technology School 90 m
Law School to Admin School 115 m
Business School to Technology School 40 m
Business School to Admin School 45 m
Technology School to Admin School 25 m
Number of computers in each of the Schools/Centre is follows:
Law school 25
Technology School 50
Admin school 125
Business School 35

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

RESOURCE BUILDING TO TRANING BUILDING 125m


RESOURCE BUILDING TO ACCOUNTS BUILDING 45m
TRANING BUILDING TO ACCOUNTS BUILDING 110m

Expected number of computers in each building is as follows:


MAIN BUILDING 15
RESOURCE BUILDING 25
TRAINING BUILDING 250
ACCOUNTS BUILDING 10
E1) Suggest a cable layout of connections between the buildings.
E2) Suggest the most suitable place (i.e. building) to house the server for this NGO. Also,
provide a suitable reason for your suggestion.
E3) Suggest the placement of the following devices with justification:
(vi) Repeater
(vii) Hub/switch
E4) The NGO is planning to connect its International office situated in Delhi. Which out of
the following wired communication links, will you suggest for a very high speed
connectivity?
(viii) Telephone analog line
(ix) Optical fibre
(x) Ethernet cable
E5)Suggest a device to prevent unauthorised access of information,and to ensure secured
internet surfing,in the buildings.

Answer :

i) Proper Layout using Star ,Ring or Bus topology preferably


ii)Training Building

88
iii)Where the distance more than 90-100 mtr .
iv)Optical fibre
v)Firewal

UNIT 7 : DATABASE CONCEPTS AND SQL

Section 1: Database Concepts

1. DATABASE: A Database is defined as an organized collection of interrelated data


that serves many applications.
2. DATABASE MANAGEMENT SYSTEM: A Database Management System
(DBMS) is a general purpose software system that facilitates the process of defining,
constructing and manipulating databases for various applications.
3. NEED FOR DBMS
1) Helps store data in a structured manner.
2) Query the Database(i.e. ask questions about the data)
3) Sort and Manipulate the Data in the Database
4) Validate the Data Entered and check for inconsistencies
5) Produce Flexible Reports
4. ADVANTAGES OF DBMS
1) Elimination of Data Redundancy/Duplication
2) Data Consistency
3) Sharing of Data
4) Reduced Programming Effort
5) Improved Data Integrity
6) Privacy and Security
7) Improved backup and recovery system
8) Economical
5. TYPES OF DBMS
1) Hierarchical DBMS
2) Network Based DBMS
3) Object Based DBMS
4) Relational DBMS
6. RELATIONAL DATABASE MANAGEMENT SYSTEM (RDBMS)

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.

Check Your Progress :

MULTIPLE CHOICE QUESTIONS

Question 1: What is a database?


(A) A collection of organized data (B) A software program used to manage data
(C) A hardware device used to store data (D) All of the above
Answer: (A)

Question 2: What are the benefits of using a database?


(A) Improved data organization and efficiency (B) Reduced data redundancy
(C) Improved data integrity (D) Improved data security
(E) All of the above
Answer: (E)

Question 3: What is the relational data model?


(A) A type of database model that stores data in tables
(B) A type of database model that stores data in hierarchies
(C) A type of database model that stores data in networks
(D) All of the above
Answer: (A)

Question 4: What is a relation in the relational data model?


(A) A table (B) A row in a table (C) A column in a table (D) None of the above
Answer: (A)

Question 5: What is an attribute in the relational data model?


(A) A column in a table (B) A row in a table (C) A table (D) None of the above
Answer: (A)

Question 6: What is the domain of an attribute?


(A) The set of possible values that the attribute can take
(B) The name of the attribute
(C) The data type of the attribute (D) None of the above

91
Answer: (A)

Question 7: What is the degree of a relation?


(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above
Answer: (A)

Question 8: What is the cardinality of a relation?


(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above
Answer: (B)

Question 9: What is a key in the relational data model?


(A) A set of attributes that uniquely identifies a tuple in a relation
(B) A set of attributes that is used to sort the tuples in a relation
(C) A set of attributes that is used to filter the tuples in a relation
(D) None of the above
Answer: (A)

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


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

ASSERTION REASONING QUESTIONS

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).

TRUE FALSE QUESTIONS


1: A database is a collection of organized data. (True)
2: The relational data model is a type of database model that stores data in hierarchies. (False)
3: A relation in the relational data model is a row in a table. (False)
4: A foreign key in the relational data model is a set of attributes in one relation that references
the primary key of another relation. (True)
5: A candidate key in the relational data model is a set of attributes that can uniquely identifies
a row in a table. (True)

SHORT ANSWER QUESTIONS (2 MARKS)


1 Mention the various advantages of DBMS.
1. Ans. The following are some of the advantages of DBMS:-
2. 1. Elimination of Data Redundancy/Duplication
3. 2.Data Consistency
4. 3.Sharing of Data
5. 4.Reduced Programming Effort etc.
2.What is the difference between an attribute and tuple?
Ans. The columns of the table are known as Attributes and the rows in the table which store the
record is known as tuples.
3.Define Degree and Cardinality.
Ans. DEGREE OF A RELATION – The total number of Attributes in a relation is known as
the Degree of the Relation.
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.

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.

SHORT ANSWER QUESTIONS (3 MARKS)


1.Mention 3 Limitations of DBMS.
Ans. The following are three Limitations of DBMS:-
a.High Cost – DBMS requires various software, hardware and highly intelligent people, for
operating and maintaining the database system, which adds cost.
b.Database Failure – If Database is corrupted due to power failure or any other reason, our
valuable data may be lost.
c.Data Quality – With increased number of users directly accessing data from a Database, there
are enormous opportunities for data damage.

Section 2: Structured Query Language (SQL)

MySQL is an open-source relational database management system.


Types of SQL Statements / Commands :
2. Data Definition Language (DDL) Statement
3. Data Manipulation Language (DML) Statement
4. Transaction Control Statement
5. Session Control Statement
6. System Control Statement
7. Embedded SQL Statement
Data Definition Language (DDL) Statements :
8. Data Definition Language (DDL) or Data Description Language (DDL) is a
standard for commands that defines the different structures in a database.
9. DDL statements are used to create structure of a table, modify the existing
structure of the table and remove the existing table.
10. Some of the DDL statements are CREATE TABLE, ALTER TABLE and DROP
TABLE.
Data Manipulation Language (DML) Statements :
11. Data Manipulation Language (DML) statements are used to access and manipulate
data in existing 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.

Commonly used data types in MySQL:


(1) CHAR :
14. CHAR should be used for storing fix length character strings.
15. Syntax: CHAR(n)
16. Fixed-length character string having maximum length n.
17. Example: CHAR(5) implies to reserve spaces for 5 characters. If data does not
have 5 characters (e.g., ‘CS’ has two characters), MySQL fills the remaining 6
characters with spaces padded on the right.

(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;

Database School is created

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>;

Check Your Progress :


MCQ
1. In a table STUDENT in MySQL database, an attribute NAME of data type
VARCHAR(20) has the value “ASEEMA SAHU”. Another attribute SUBJECT of
data type CHAR(10) has value “CS”. How many characters are occupied by attribute
NAME and attribute SUBJECT respectively?
R. 11, 10
S. 11, 2
T. 12, 3
U. 20, 10
2. Identify the MySQL Commands that belongs to DML category :
V. ALTER
W. DROP
X. DELETE
Y. CREATE
3. Consider the following Statements :
Statement – 1 : UNIQUE constraint ensures that all the values in a column are distinct
/ unique.
Statement – 2 : MySQL is an open-source relational database management system.
Z. Only Statement-1 is True
AA. Only Statement-2 is True
BB. Both Statements are True.
CC. Both Statements are False.
4. Fill in the blank:
______________________________ are used to define the different structures in a
database.
DD. Data Definition Language (DDL) Statement
EE. Data Manipulation Language (DML) Statement
FF. Transaction Control Statement
GG. Session Control Statement
5. Naresh wants to create an attribute for admission number. Which will be the most
suitable data type for admission number which can accommodate admission numbers
with 4 digits ?
HH. VARCHAR(2)
II. CHAR(3)
JJ. INT
KK. DATE

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

ADMN INT PRIMARY KEY


The first record inserted in the table REMEDIAL successfully is as follows :
SNAME ROLL FEES ADMN
AZAD 10 3500 4585
SARKAR
11. Assertion(A):
The MySQL statement :
INSERT INTO REMEDIAL (ROLL, FEES, ADMN) VALUES (11, 1800, 4986);
will generate an ERROR and record will not be inserted.
Reasoning(R):
Field 'SNAME' cannot be an empty or NULL value as the Constraint assign is NOT
NULL.

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:

16. MySQL is an open-source relational database management system.


17. All Candidate Keys are Primary Keys but all Primary keys are not Candidate Keys.
18. MySQL statement to delete a table STUDENT from the database SCHOOL is
DELETE TABLE STUDENT;
19. ALTER TABLE statement is used to make changes in the structure of a table like
adding, removing or, changing datatype of column(s).
20. DDL (Data Definition Language) includes SQL statements such as, CREATE
TABLE, ALTER TABLE and DROP TABLE.

Short Answer Type Questions


21. Write MySQL statements for the following:
i. To create a database named SCHOOL.
ii. To create a table named REMEDIAL based on the following specification:
Field Datatype Constraints
SNAME VARCHAR( NOT NULL
20)
ROLL INT UNIQUE
FEES FLOAT

ADMN INT PRIMARY KEY


22. Mr. Kareem Sen has just created a table named “STUDENT” containing columns
SNAME, SUBJECT and FEES. After creating the table, he realized that he has
forgotten to add a PRIMARY KEY column in the table. Help him in writing an SQL
command to add a PRIMARY KEY column ADMN of integer type to the table
Employee.
23. Zenith is working in a database named SCHOOL, in which she has created a table
named “STUDENT” containing columns ADMN, SNAME, GENDER and
CATEGORY. After creating the table, she realized that the attribute, GENDER has to
be deleted from the table and a new attribute FEES of data type FLOAT has to be
added. This attribute FEES cannot be left blank. Help Zenith to write the commands
to complete both the tasks.
24. (i) State one difference between DDL and DML statements in MySQL.
(ii) Write the MySQL statement to delete the database named “SCHOOL”.
25. Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER,
DROP

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.

(ii) DROP DATABASE SCHOOL;


25. DDL - ALTER, DROP
DML - INSERT, UPDATE

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.

4. Aliasing and the DISTINCT Clause:


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

5.- 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.

7. Handling NULL Values:


- NULL values represent missing or unknown data in a database.
- SQL provides functions like IS NULL and IS NOT NULL to filter or identify NULL values
in queries.
- Proper handling of NULL values is crucial to ensure accurate data retrieval.

102
Check Your Progress :

Q 1 to Q 5 are ASSERTION ( A ) and REASONING ( R ) based questions.

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 correct explanation for A.
c.A is true but R is false.
d.A is false but R is true.

1. Assertion ( A ) : ORDER BY Clause is used to sort the records.


Reason ( R ) : For sorting, the keywords ASC and DESC are used.

Answer : Option (A) is correct

2. Assertion ( A ) : The UNIQUE keyword ensures no duplicate value in table.


Reason ( R ) : DISTINCT is similar to UNIQUE.

Answer : Option (A) is correct

3. Assertion ( A ) : SELECT provides clauses for summarising results.


Reason ( R ) : The GROUP BY clause allows to create summarized results.

Answer : Option (A) is correct

4. Assertion ( A ) : LIKE is a Logical operator used with WHERE clause.


Reason ( R ) : Wildcard characters are used with LIKE operator.

Answer : Option (A) is correct


5. Assertion ( A ) : FLOAT and DOUBLE are data types
Reason ( R ) : Both can hold any number upto 23 digits.

Answer : Option (C) is correct

VERY SHORT ANSWER QUESTIONS ( 1 Mark each )


1. Which keyword is used to sort the records of a table in descending order ?
Answer : DESC
2. Which clause is used to sort the records of a table ?
Answer : ORDER BY
3. Which command is used to modify the records of the table ?
Answer : UPDATE
4. Which clause is used to remove the duplicating rows of the table?
Answer : DISTINCT

103
5. What is the use of IS NULL operator ?
Answer : It checks whether the column has null value / no value .

SHORT ANSWER QUESTIONS ( 2 Marks each )


Q1. What is the use of wildcard characters ?
Answer : The wildcard characters are used with the LIKE operator to search a value
similar to a specific pattern in a column. There are two wildcard characters :
% it represents 0 or more number of characters
_ it represents a single character

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

Answer : a) INSERT INTO SALES VALUES(‘A101’, ‘SHAMPOO’ ,200 )


b) DELETE FROM SALES WHERE PROD_ID = ‘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;

- `table_name`: The name of the table you want to update.


- `SET`: Specifies the columns to be updated along with their new values.
- `WHERE`: Defines the conditions that determine which rows to update.

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:

DELETE FROM table_name


WHERE condition;
- `table_name`: The name of the table from which you want to delete rows.
- `WHERE`: Specifies the conditions that determine which rows to delete.

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:

DELETE FROM Orders


WHERE OrderDate < '2023-01-01';
This query will remove all rows from the "Orders" table where the "OrderDate" is earlier than
January 1, 2023.

Section 6. Aggregate Functions

- In the realm of databases, aggregate functions are essential tools for data summarization and
analysis.
- MAX : Computes the maximum value within a given column.
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 7. GROUP BY and HAVING Clause for Data Summarization


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

Section 8.Cartesian Product on Two Tables


- The Cartesian product, also known as a cross join, is a mathematical operation that combines
every row from one table with every row from another table.
- It results in a table with the number of rows equal to the product of the rows in both tables.
- Typically, Cartesian products are avoided in practice due to their large size and potential
performance issues.

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.

Check Your Progress :

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

Short Question Answer


Q.1 Explain the cartesian product of two relations
Ans. The cartesian product is a binary operation and is donated by a cross (X). The Cartesian
product of two relations A and B is written as A X B. The cartesian product yields a new
relation which has a degree (number of attributes) equal to the sum of the degrees of the two
relations operated upon. The number of tuples (cardinality) of the new relation is the product
of the number of tuples of the two relations operated upon. The cartesian product of two
relations yields a relation with all possible combinations of the tuples of the two relations
operated upon.
Q.2 What are aggregate functions ? How are they useful ?
Ans Aggregate functions are the functions that work on multiple tuples’ values for an attribute
and return single summarised values for a group of tuples.
Following are some commonly used aggregate functions in SQL:
AVG() Returns the average value from specified columns.
COUNT() Returns number of table rows.
MAX()Returns the largest value among the records.
MIN() Returns smallest value among the records.
SUM() Returns the sum of specified column values.

Q.3 What is the use of Group by Clause ? Give examples

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.

Short Answer- ( 3 marks question )


1- Consider the following tables EMPLOUYEE and SALGRADE and answer the
following parts of this question:
Table: EMPLOYEE
ECODE NAME DESIG SGRADE DOJ DOB
101 Abdul EXECUTIV S03 23-Mar-2003 13-Jan-1980
102 Ahmad E S02 12-Feb-2010 22-Jul-1987
103 Ravi HEAD-IT S03 24-Jun-2009 24-Feb-1983
105 Chander RECEPTIO S02 11-Aug- 03-Mar-1984
108 John Cen NIST S01 2006 19-Jan-1982
Naza Ameen GM 29-Dec-2004
Priyam Sen CEO
Table: SALGRADE
SGRADE SALARY HRA
S01 56000 18000
S02 32000 12000
S03 2400 8000

Give the output of the following SQL queries:


1. SELECT COUNT (SGRADE), SGRADE FROM EMPLOYEE GROUP BY
SGRADE;
2. SELECT MIN(DOB), MAX(DOJ) FROM EMPLOYEE ;
3. SELECT NAME, SALARY FROM EMPLOYEE E, SALGRADE S
1. WHERE E.SGRADE = S.SGRADE AND E.ECODE < 103;
4. SELECT SGRADE, SALARY + HRA FROM SALGRADE WHERE SGRADE =
‘S02’ ;
110
Ans.
1. COUNT SGRADE
1. 2 S03
2. 2 S02
2. S01

3. 13-JAN-1980 12-FEB-2010

4. NAME SALARY
1. Abdul Ahmad 24000
2. Ravi Chander 32000

5. SGRADE SALARY + HRA


1. S02 44000

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

3- Give output for following SQL queries as per given table(s)


Table : PRODUCT
P_ID ProductName Manufacturer Price
TP01 Talcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95

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

1. SELECT DISTINCT City FROM Client ;


2. SELECT Manufacturer, MAX(Price), Min(Price), Count(*) FROM Product GROUP
BY Manufacturer;
3. SELECT ClientName , ProductName FROM Product, Client
WHERE Client.P_Id = Product.P_Id ;
4. SELECT ProductName, Price * 4 FROM Product ;

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

4. Talcom Powder 160


1. Face Wash 180
2. Bath Soap 220
3. Shampoo 480
4. Face Wash 350
CASE BASED STUDY - ( 4 Marks )
1- Consider the following tables ITEM and CUSTOMER, Write SQL commands for the
following statements:
Table : ITEM
i_ID ItemName Manufacturer Price
PC01 Personal Computer ABC 35000
LC05 Laptop ABC 55000
PC03 Personal Computer XYZ 32000
PC06 Personal Computer COMP 37000
LC03 Laptop PQR 57000

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

I. To display the details of those Customers whose city is Delhi


II. To display the details of Item whose price is in the range of 35000 to 55000 (Both
values included)
III. To display the CustomerName, City from table Customer, and ItemName and price
from table item, with their corresponding matching I_ID
IV. To increase the price of all items by 1000 in the table Item.

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.

CODE FOR CREATING A MYSQL DATABASE THROUGH PYTHON


import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="mohana", password="mohana")

mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

CODE FOR CREATING A TABLE IN MYSQL THROUGH PYTHON


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

CODE FOR INSERTING DATA IN A MYSQL TABLE THROUGH PYTHON


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

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)

CODE FOR DELETING A RECORD FROM MYSQL TABLE USING PYTHON


import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",
database="mydatabase")
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE name = 'XYZ'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")

CODE FOR UPDATING A RECORD FROM MYSQL TABLE USING PYTHON

import mysql.connector

mydb =
mysql.connector.connect(host="localhost",user="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-3 True or False? A cursor is used to create a database.


A. True
B. False

Q-4 Which of the following is true about The PYTHONPATH Variable?


A. The PYTHONPATH is an environment variable
B. It consists of a list of directories
C. The syntax of PYTHONPATH is the same as that of the shell variable PATH
D. All of the above
Ans.D

Q-5 CONNECT() function in SQL is used for:


A. To connect to database. B. To open database
C. To create database D. All of the above
Ans.D

Q-6 which method is used to retrieve N number of records


A. fetchone() B. fetchall() C. fetchmany() D. fetchN()
Ans.C

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

Q-9 In python, connect() returns _________.


A. Connection object. B. Database object C. Database name D. Connector class
Ans.A

Q-10 In python, execute() method can execute only ________ .


A. Only DQL & DML statements B. Only DML statements
C. Only DQL statements. D. DDL, DML & DQL statements.
Ans.D

B. ASSERTION and REASONING based questions.

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

4.Assertion(A): MySqldb is an interface for connecting to a MySql database servers to


Python
Reason(R):exit() function is used to close the connection to a database
Ans. c

5.Assertion(A):fetchone() returns the next row as a query of the sequence


Reason(R):fetchone() raises an exception if there is no resultset
Ans. c

C. TRUE FALSE QUESTION ON MYSQL DATABASE CONNECTIVITY


1. To create a database in MySQL, use the "CREATE DATABASE" statement (TRUE)

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.

2. What is a cursor in the context of MySQL?


ANS. A cursor is a pointer that points to a specific location in a database table. In MySQL,
cursors are used to iterate through the rows of a table and retrieve data from them.

3. What’s the difference between autocommit and commit?


ANS. Autocommit is a database feature that automatically commits changes to the database as
soon as they are made. This means that changes are immediately visible to other users and
there is no need to explicitly call the commit() method. Commit, on the other hand, is a
database feature that allows changes to be made to the database and then explicitly committed
by the user. This allows the user to control when changes are made visible to other users.

4. How can you check if a table exists in MySQL?


ANS. You can check if a table exists in MySQL by using the SHOW TABLES command.
This will show you a list of all the tables in the database. If the table you are looking for is not
in the list, then it does not exist.

5. How do you disconnect from the database?


ANS.Use the close() method. db.close() closes the connection from the database.

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.

Q5. Explain the following 'results' retrieval methods


A. fetchone () B. rowcount () C. fetchall ()
Ans: (A) fetchone() :- The fetchone() method will return only one row from the result set in the
form of tuple containing a record.
(B) rowcount() :- cursor.rowcount() that always return how many records have been retrieved
so for using any of the fetch..() methods.
(C) fetchall() :- The fetchall() method return all the rows from the result set in the form of a
tuple congaing the records.

F. CASE STUDY BASED QUESTIONS

1. A STUDENT HAS WRITTEN THE FOLLOWING CODE


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

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()

IMPORTANT CONNECTIVITY METHODS :

Connectivity Basics: Important functions and its purpose :


- connect( ): Establishes a connection to the database.
- cursor( ): Creates a cursor object to execute SQL queries.
- execute( ): Executes SQL commands.
- commit( ): Saves changes made during the transaction.
2. Fetching Data:
- fetchone( ): Retrieves the next row of a query result set.
- fetchall( ): Fetches all rows of a query result set.
- rowcount: Returns the number of rows affected by the last executed command.
3. Creating Database Applications:

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

# import the mysql-python connector module


import mysql.connector
# Establishing a connection to the database
conn = psycopg2.connect(database="mydb", user="user", password="password",
host="localhost", port="5432")
# Creating a cursor object to execute queries
cur = conn.cursor()
# Executing a query using %s format specifier
cur.execute("INSERT INTO table_name (column1, column2) VALUES (%s, %s)", (value1,
value2))
# Fetching data using fetchone() or fetchall()
data = cur.fetchone()
# Committing changes and closing the connection
conn.commit()
conn.close()

Check your Progress :


Multiple Choice Questions (MCQ) :
1. What does the `connect()` function do in database connectivity?
A. Closes the database connection B. Establishes a connection to the database
C. Deletes the database D. Fetches data from the database
Correct Answer: B

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

Assertion Reason Questions :


1. Assertion: `fetchall()` retrieves only the first row of the query result.
Reason: `fetchall()` function fetches all rows of the query result set.
Correct Answer: False. Assertion is incorrect, and the Reason is incorrect.
2. Assertion:The `rowcount` attribute is used to get the number of rows affected by the last
executed command.
Reason: It helps in determining the number of columns in the query result.
Correct Answer: True. Assertion is correct, and the Reason is correct.
3. Assertion: `commit()` is essential after executing SQL commands to save the changes
made during the transaction.
Reason: It is necessary to close the database connection.
Correct Answer: True. Both Assertion and Reason are correct, and the Reason is the correct
explanation of the Assertion.
4. Assertion: `%s` format specifier in SQL queries helps prevent SQL injection attacks.
Reason: It dynamically inserts values into queries, enhancing flexibility and security.
Correct Answer: True. Both Assertion and Reason are correct, and the Reason is the correct
explanation of the Assertion.
5. Assertion: `connect()` function creates a cursor object for executing SQL commands.
Reason: `cursor()` function establishes a connection to the database.
Correct Answer: False. Assertion is incorrect, and the Reason is incorrect.

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)

Short Answer (SA-1) Questions :


1. Explain the purpose of the `fetchall()` function in Python's database connectivity.
2. How is the `rowcount` attribute helpful while working with database connectivity?
3. Describe the role of the `execute()` function in executing SQL queries.
4. What does SQL injection mean, and how can it be prevented in Python's database
applications?
5. Briefly explain the significance of the `commit()` function in database transactions.

Short Answer (SA-2) Questions :


1. Discuss the steps involved in creating a database connectivity application using Python.
2. Compare and contrast `fetchone()` and `fetchall()` functions in Python's database
connectivity.
3. Explain the importance of using placeholders like `%s` in SQL queries with examples.
4. Describe the use of `format()` function in dynamically inserting values into SQL queries.
Provide an example.
5. How can the `rowcount` attribute be used to determine the success of an SQL query in
Python?
6. Discuss two common security risks associated with database connectivity in Python and
how to mitigate them.
7. Explain the process of creating a cursor object and its significance in database operations
using Python.
8. How does `commit()` function contribute to data integrity in database transactions?
9. What is the role of the `rollback()` function in database transactions? Provide an example
scenario.
10. Explain how exceptions are handled in Python's database connectivity to manage errors in
SQL queries.

124

You might also like