SSM Xii Computer Science
SSM Xii Computer Science
CHIEF MENTOR
Smt. Sona Seth, Deputy Commissioner, KVS Regional Office Lucknow
MENTOR
Sh. Anup Kumar Awasthi, Assistant Commissioner, KVS Regional Office Lucknow
Smt. Archana Jaiswal, Assistant Commissioner, KVS Regional Office Lucknow
Sh. Vijay Kumar, Assistant Commissioner, KVS Regional Office Lucknow
COORDINATOR
Sh. Samrat Kohli, Vice-Principal, PM SHRI KV OEF No. 1 Kanpur
CONTENT DEVELOPMENT TEAM
Sh. Prateek Rastogi, PGT (Comp. Sc.), PM SHRI KV AFS Memaura Lucknow
Sh. Sanjeev Kumar, PGT (Comp. Sc.), PM SHRI KV Hardoi
Sh. Mehtav Ul Ghani, PGT (Comp. Sc.), KV IVRI Bareilly
Sh. Nitin Rathore, PGT (Comp. Sc.), KV IFFCO Bareilly
Sh. Vinod Kumar Verma, PGT (Comp. Sc.), PM SHRI KV OEF No. 1 Kanpur
Sh. Tarun Kumar Vishwakarma, PGT (Comp. Sc.), PM SHRI KV Raebareli 1 st Shift
Sh. Mohd. Hashim, PGT (Comp. Sc.), PM SHRI KV OCF Shahjahanpur 1 st Shift
Sh. Chandra Prakash Sahu, PGT (Comp. Sc.), PM SHRI KV Shrawasti
IMPROVEMENT & COMPILATION
Smt. Nidhi Mishra, PGT (Comp. Sc.), PM SHRI KV Balrampur
MLL Material, Class XII Computer Science, KVS RO Lucknow 2
2
MLL Material, Class XII Computer Science, KVS RO Lucknow 3
CONTENT
3
MLL Material, Class XII Computer Science, KVS RO Lucknow 4
Python Basics:
Overview of Python: Python is a high-level, interpreted programming language known for its simplicity and
readability. It's widely used in web development, data science, automation, and more.
Python Modes
1. Interactive Mode:
o Directly type code in the interpreter.
o Immediate execution.
2. Script Mode:
o Write code in a file (.py).
o Run the script via terminal.
IDEs
1. IDLE: Built-in, simple.
2. PyCharm: Feature-rich, for professionals.
3. VS Code: Lightweight, extensible.
4. Jupyter Notebook: Web-based, for data science.
5. Spyder: Scientific computing.
Variables
Definition: A variable is a name that refers to a value.
Usage: You can create a variable by assigning a value to it using the = operator.
Example:
age = 18
name = “Ravi”
Data Types in Python
Numbers:
Integers (int): Whole numbers, e.g., 10
Floating-point (float): Decimal numbers, e.g., 10.5
Complex (complex): Complex numbers, e.g., 3+4j
Strings: Text data enclosed in quotes, e.g., "Hello"
Lists: Ordered, mutable collections of items, e.g., [1, 2, 3]
Tuples: Ordered, immutable collections of items, e.g., (1, 2, 3)
Dictionaries: Unordered collections of key-value pairs, e.g., {"name": "Alex", "age": 18}
Boolean: Represents True or False.
Operators in Python
1. Arithmetic Operators:
o Used for mathematical operations.
o Examples: + (addition), - (subtraction), * (multiplication), / (division), % (modulus), **
(exponentiation), // (floor division).
2. Relational Operators:
o Used for comparison between values.
o Examples: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or
equal to), <= (less than or equal to).
3. Logical Operators:
o Used for logical operations.
o Examples: and, or, not.
4
MLL Material, Class XII Computer Science, KVS RO Lucknow 5
4. Bitwise Operators:
o Used for binary operations on integers.
o Examples: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
5. Assignment Operators: Assignment operators are used to assign values to variables. The most common
assignment operator is =. However, Python also provides compound assignment operators, which are
shorthand for performing an operation and assignment simultaneously.
6. Identity Operators: Used to check if two variables refer to the same object.
Examples: is, is not.
7. Membership Operators: Used to test if a value is a member of a sequence (like a string, list, or tuple).
Examples: in, not in.
Expression Solving:
When solving expressions in Python, you should follow these rules and guidelines to ensure correctness. These
rules align with operator precedence, associativity, and evaluation order.
1. Operator Precedence: Python follows a specific hierarchy of operations when evaluating expressions.
Operators with higher precedence are evaluated before those with lower precedence.
Precedence Operator Description
Highest () Parentheses (grouping)
** Exponentiation
+, - (unary) Unary plus and minus
*, /, //, % Multiplication, division, floor
division, modulo
+, - Addition, subtraction
<, <=, >, >= Comparison operators
==, != Equality operators
not Logical NOT
and Logical AND
Lowest or Logical OR
Example:
5
MLL Material, Class XII Computer Science, KVS RO Lucknow 6
5. Chained Comparisons : Python allows chained comparisons, which are evaluated in order and are
equivalent to logical and.
Example:
print(3 < 5 < 10) # Equivalent to (3 < 5) and (5 < 10)
# Output: True
6. Logical Operator Short-Circuiting
• Logical operator AND and OR short-circuit, meaning they stop evaluation as soon as the result is
determined.
• and: Stops if the first condition is False.
• or: Stops if the first condition is True.
Example:
print(False and (1 / 0)) # Output: False (no division by zero error)
print(True or (1 / 0)) # Output: True (no division by zero error)
7. Implicit Type Conversion (Type Coercion)
• Python tries to automatically convert types where applicable, such as integers to floats during
arithmetic.
Example:
print(5 + 2.5) # Output: 7.5 (int 5 is converted to float)
8. Errors in Expressions
• Division by zero (10 / 0) results in a ZeroDivisionError.
• Mixing incompatible types (e.g., 5 + "5") results in a TypeError.
Finding Errors (in given Python code): To find errors in a given Python code,
Types of Errors:
6
MLL Material, Class XII Computer Science, KVS RO Lucknow 7
7
MLL Material, Class XII Computer Science, KVS RO Lucknow 8
A: Python supports three types of numeric data types: integers (int), floating-point numbers (float), and
complex numbers (complex).
Q: Write a Python program to add two complex numbers.
A: z1 = 2 + 3j
z2 = 1 + 4j
result = z1 + z2
print("Sum of the complex numbers:", result)
Q: What is a string in Python?
A: A string is a sequence of characters enclosed in single quotes (') or double quotes ("). Example:
str1 = 'Hello'
str2 = "World"
Q: How do you access individual characters in a string?
A: You can access individual characters in a string using indexing. Example:
str1 = "Hello"
first_char = str1[0] # Output: 'H'
Q: How do you split a string into a list of substrings?
A: You can use the split() method to split a string into a list of substrings. Example:
str1 = "Hello, World!"
substrings = str1.split(", ")
print(substrings) # Output: ['Hello', 'World!']
Q: Write a Python program to join a list of strings into a single string.
A: words = ["Hello", "World"]
sentence = " ".join(words)
print("Joined string:", sentence)
Q: What is a list in Python?
A: A list is an ordered, mutable collection of elements enclosed in square brackets ([]). Example:
my_list = [1, 2, 3, 4, 5]
Q: Write a Python program to append an element to a list.
A: my_list = [1, 2, 3]
my_list.append(4)
print("Updated list:", my_list) # Output: [1, 2, 3, 4]
Q: How do you remove an element from a list by value?
A: You can use the remove() method. Example:
my_list = [1, 2, 3, 4]
my_list.remove(3)
print("Updated list:", my_list) # Output: [1, 2, 4]
Q: How do you extend a list with another list?
A: You can use the extend() method. Example:
list1 = [1, 2, 3]
list2 = [4, 5]
list1.extend(list2)
print("Extended list:", list1) # Output: [1, 2, 3, 4, 5]
Q: Write a Python program to count the occurrences of an element in a list.
A: my_list = [1, 2, 2, 3, 4, 2]
count = my_list.count(2)
print("Occurrences of 2:", count) # Output: 3
Q: How do you reverse a list in Python?
A: You can use the reverse() method. Example:
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
my_list.clear()
8
MLL Material, Class XII Computer Science, KVS RO Lucknow 9
9
MLL Material, Class XII Computer Science, KVS RO Lucknow 10
print("Hello, World!"
A. The error is a missing closing parenthesis ). The correct code should be:
print("Hello, World!")
Q. What is a NameError in Python? Give an example.
A. A NameError occurs when a variable or function name is not found in the local or global scope.
Example: print(x) # NameError because 'x' is not defined
Q. The code provided below is intended to swap the first and last elements of a given tuple. However, there
are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the
corrections made
Basic Syntax and Output: Missing parentheses in the print() function or incorrect indentation.
Comments: Not using comments effectively to explain the code.
Variables and Data Types: Mixing up data types or using incorrect type conversions.
Input from the User: Forgetting to convert the input to the desired data type.
Python Data Types-
Numbers
Misinterpreting Division: Confusing division operators (/ for floating-point division and // for floor
division).
o Correct: 10 / 3 results in 3.333..., 10 // 3 results in 3.
Mixing Types in Arithmetic Operations: Not properly converting data types before performing
operations.
o Example: Adding a string and an integer directly without type conversion can cause
errors.
o Correct: int('5') + 10 results in 15.
Strings
Indexing Errors: Using incorrect indices when accessing string characters.
o Example: Accessing str1[5] when str1 length is only 5 causes an IndexError.
Immutable Nature of Strings: Trying to modify a string in place.
o Correct: To modify, create a new string. Example: new_str = old_str.replace('o', 'a').
Lists
List Indexing Mistakes: Accessing elements using out-of-bound indices.
o Correct: Ensure indices are within the list length. Example: my_list[0] for the first
element.
Appending Errors: Forgetting to use the append() method correctly.
o Correct: my_list.append(4) to add an element.
10
MLL Material, Class XII Computer Science, KVS RO Lucknow 11
Using extend() and append() Incorrectly: Confusing the behavior of extend() and append().
o Correct: my_list.extend([4, 5]) vs. my_list.append([4, 5]).
Tuples
Confusing Lists with Tuples: Trying to modify a tuple.
o Correct: Tuples are immutable. Example: my_tuple = (1, 2, 3) cannot be changed.
Using Parentheses Incorrectly: Omitting parentheses for single-element tuples.
o Correct: single_element_tuple = (5,).
Dictionaries
Using Incorrect Keys: Trying to use mutable types like lists as dictionary keys.
o Correct: Use immutable types like strings, numbers, or tuples as keys. Example: my_dict
= {'name': 'Alice', 'age': 25}.
Accessing Non-Existent Keys: Accessing keys that don't exist in the dictionary.
o Solution: Use get() method to avoid KeyError. Example: my_dict.get('address').
Type Conversion
Type Conversion Errors: Forgetting to convert types when necessary.
o Correct: Use conversion functions like int(), float(), str(). Example: int('123') to convert
string to integer.
Implicit Type Conversion Misunderstanding: Assuming Python will always handle type conversion
automatically.
o Solution: Explicitly convert types when required to avoid errors.
Operators-
Confusing = and == Operators:
o Mistake: Using = instead of == in conditional statements.
Example: if a = 5: # Incorrect
o Correction: if a == 5: # Correct
Misunderstanding the Use of Logical Operators:
o Mistake: Incorrectly using and, or, and not.
Example: if a and b == True: # Incorrect
o Correction: if a and b: # Correct
Neglecting Operator Precedence:
o Mistake: Not using parentheses to control the order of operations.
Example:
result = 10 + 2 * 5 # Incorrect if the intended result was (10 + 2) * 5
o Correction: result = (10 + 2) * 5 # Correct
Misusing the Identity Operators (is, is not):
o Mistake: Using is instead of == for value comparison.
Example:
if a is 5: # Incorrect for value comparison
o Correction: if a == 5: # Correct
Overlooking the Use of Floor Division:
o Mistake: Using / instead of // for integer division.
Example:
result = 10 / 3 # Incorrect if the intended result is an integer
o Correction: result = 10 // 3 # Correct
Expression Solving:
Neglecting Operator Precedence:
o Mistake: Not following the correct order of operations.
o Example:
result = 3 + 5 * 2 - 8 / 4 # Incorrect understanding of precedence
o Correction:
11
MLL Material, Class XII Computer Science, KVS RO Lucknow 12
12
MLL Material, Class XII Computer Science, KVS RO Lucknow 13
Name of Unit: UNIT – I (Computational Thinking-and Name of Chapter: Revision of Python topics covered
Programming II) in Class XI.
Topic: Most commonly used built-in functions and methods of string, list, tuple and dictionary, use of math and
statistics functions
Gist of the topic: Most commonly used built-in functions and methods of STRING
13
MLL Material, Class XII Computer Science, KVS RO Lucknow 14
True
9 <string>.islower() It returns True if all cased characters in the string are
lowercase. There must be at least one cased character. It
returns False otherwise.
>>>'CBSEEXAMINAtion2025'.islower()
False
>>> 'cbse2025'.islower()
True
10 <string>.isspace() It returns True if there are only whitespace characters in
the string. There must be at least one character. It returns
False otherwise.
>>>'cbse 2025'.isspace()
False
>>> ' '.isspace()
True
11 <string>.isupper() It tests whether all cased characters in the string are
uppercase and requires that there be at least one cased
character. Returns True if so and False otherwise.
>>>'CBSEEXAMINAtion2025'.isupper()
False
>>> 'CBSE2025'.islower()
True
12 <string>.lower() It returns a copy of the string converted to lowercase.
>>>'CBSEEXAMINAtion2025'.lower()
'cbseexamination2025'
13 <string>.upper() It returns a copy of the string converted to uppercase.
>>>'CBSEEXAMINAtion2025'.upper()
'CBSEEXAMINATION2025'
14 <string>.Istrip() It returns a copy of the string with leading white- spaces
removed.
>>> ' CBSE2025 '.lstrip()
'CBSE2025 '
15 <string>.rstrip() It returns a copy of the string with trailing white-spaces
removed.
>>> ' CBSE2025 '.rstrip()
' CBSE2025'
16 <string>.strip() It returns a copy of the string with leading and trailing
whitespaces removed.
>>> ' CBSE2025 '.strip()
'CBSE2025'
17 <string>.title() It returns a title-cased version of the string where all words
start with uppercase characters and all remaining letters
are lowercase.
>>> 'computer science'.title()
'Computer Science'
18 <string-replace(old, new) It returns a copy of the string with all occurrences of
substring old replaced by new string.
>>>'CBSE EXAM 2025'.replace('CBSE','KVS')
'KVS EXAM 2025'
19 <string>.join(<string iterable) It joins a string or character (i.e. <str>) after each member
of the string iterator i.e., a string-based sequence.
14
MLL Material, Class XII Computer Science, KVS RO Lucknow 15
>>>'**'.join('CBSE')
‘C**B**S**E'
20 <string>.split(<string/char>) It splits a string (i.e. <str>) based on the given string or
character (i.e., string/char>) and returns a list containing
split strings as members.
>>> 'CBSE EXAMINATION 2025'.split()
['CBSE', 'EXAMINATION', '2025']
>>> 'CBSE EXAMINATION 2025'.split('E')
['CBS', ' ', 'XAMINATION 2025']
21 <string>.partition(<separator It splits the string at the first occurrence of separator, and
string>) returns a tuple containing three items as string till
separation, separator and the string after separator.
>>> 'CBSE EXAMINATION 2025'.partition(' ')
('CBSE', ' ', 'EXAMINATION 2025')
22 <string>.swapcase() It covert lower case characters into upper case characters
and upper case characters into lower case characters.
>>>'CBSEEXAMINAtion2025'.swapcase()
'cbseexaminaTION2025'
Questions and Answers:
1 Select the correct output of the following code :
event=" G20 Presidency@2023"
L=event.split()
print(L{::-2])
Ans. ['Presidency@2023']
2. Assertion - The expression "HELLO" . sort ( ) in Python will give a error.
Reason - sort ( ) does not exist as a method/function for strings in Python.
A & R both are True and R is correct explanation of A
3. What is the output of the expression?
STR=”trip@split”
print(STR.rstrip(“t”))
(A) rip@spli (B) trip@spli (C) rip@split (D)rip@spil
4 What will be the output of the following code snippet?
gist=”Old is Gold”
X=gist.partition(“s”)
print(X[-1:-3])
(A) () (B) (' Gold') (C ) (' Gold', 'is') (D) None of the above
5 Write the output:-
myTuple =("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
(a) #John#Peter#Vicky (b) John#Peter#Vicky
(c) John#Peter#Vicky# (d)#John#Peter#Vicky#
6 Select the correct output of the code:
s = "Question paper 2024-25"
s= s.split('2')
print(s)
(a) ['Question paper ', '0', '4', '-', '5']
(b) ('Question paper ', '0', '', '-', '')
(c) ['Question paper ', '0', '4-', '5']
(d) ('Question paper ', '0', '4', '', '-', '5')
15
MLL Material, Class XII Computer Science, KVS RO Lucknow 16
c) (‘a’,’@’,’b@c@d’) d) [‘a’,’@’,’b@c@d’]
[‘a’,’b’,’c’,’d’] [‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
Common Mistakes committed by students while writing the answer:
Differentiate between split() & partition() function.
Use of replace function.
Gist of the topic: Most commonly used built-in functions and methods of list
s1 = 'sanju'
List from string l5 = list(s1)
print(l5) # OUTPUT – ['s', 'a', 'n', 'j', 'u']
16
MLL Material, Class XII Computer Science, KVS RO Lucknow 17
print(lst1)
l2 = [1, 2]
lst1.append(l2)
print(lst1)
OUTPUT – [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 'sanjeev']
[1, 2, 3, 4, 5, 6, 7, 'sanjeev', [1, 2]]
OUTPUT –[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 7, 8]
[1, 2, 3, 4, 5, 7, 8, 's', 'a', 'n', 'j', 'e', 'e', 'v']
[1, 2, 3, 4, 5, 7, 8, 's', 'a', 'n', 'j', 'e', 'e', 'v', 2]
TypeError
5 insert() lst1 = [1, 2, 3, 4, 5, 6]
insert element at desired place lst1.insert(0,5)
print(lst1)
lst1.insert(len(lst1),50)
print(lst1)
lst1.insert(3,75)
print(lst1)
OUTPUT –[5, 1, 2, 3, 4, 5, 6]
[5, 1, 2, 3, 4, 5, 6, 50]
[5, 1, 2, 75, 3, 4, 5, 6, 50]
6 count() lst1 = [5, 5, 3, 4, 5, 6]
counts occurrence of an element. print(lst1.count(5)) # OUTPUT – 3
7 index() lst1 = [1, 2, 3, 4, 5, 6]
gives index of first occurrence of print(lst1.index(4))
element. print(lst1.index(44))
OUTPUT – 3
ValueError: 44 is not in list
8 remove() lst1 = [1, 2, 3, 4, 5, 6]
remove element from the List lst1.remove(5)
using. If value doesn’t exists than print(lst1)
ValueError. lst1.remove(30)
print(lst1)
17
MLL Material, Class XII Computer Science, KVS RO Lucknow 18
OUTPUT –[1, 2, 3, 4, 6]
ValueError
9 clear() lst1 = [1, 2, 3, 4, 5, 6]
removes all elements from List. print(lst1)
lst1.clear()
print(lst1)
OUTPUT –[1, 2, 3, 4, 5, 6]
[]
10 pop() lst1 = [1, 2, 3, 4, 5, 6]
remove element from the List lst1.pop()
using index value. If list is empty print(lst1)
than IndexError. lst1.pop(3)
print(lst1)
OUTPUT –[1, 2, 3, 4, 5]
[1, 2, 3, 5]
11 reverse() lst1 = [5, 5, 3, 4, 5, 6]
reverse the existing List inplace. lst1.reverse()
print(lst1)
OUTPUT – [6, 5, 4, 3, 5, 5]
12 sort() lst1 = [5, 5, 3, 4, 5, 6]
sorts the List in Ascending/ lst1.sort()
Descending Order. print(lst1)
lst1 = [5, 5, 3, 4, 5, 6]
lst1.sort(reverse = True)
print(lst1)
OUTPUT –[3, 4, 5, 5, 5, 6]
[6, 5, 5, 5, 4, 3]
13 sorted() lst1 = [5, 5, 3, 4, 5, 6]
create a new list and assign l2 =sorted(lst1)
existing List in Ascending/ print(l2)
Descending Order. No change in lst1 = [5, 5, 3, 4, 5, 6]
existing List. l2 = sorted(lst1, reverse = True)
print(l2)
OUTPUT –[3, 4, 5, 5, 5, 6]
[6, 5, 5, 5, 4, 3]
14 max() lst1 = [1, 2, 3, 4, 5, 6]
min() print(max(lst1))
sum() print(min(lst1))
gives maximum, minimum value if print(sum(lst1)
List contains same type of Values.
sum() finds sum of numbers. OUTPUT – 6
1
21
Questions and Answers:
18
MLL Material, Class XII Computer Science, KVS RO Lucknow 19
7 A. Write the python statement for each of the following tasks using BUILT-IN
functions/methods only:
1. To check whether all the characters in the string S1 are digits or not. -------------- Ans.
S1.isdigit()
2. To delete the elements from index no 3 to 7 in the list
L1. –-- Ans. del L1[3:8]
OR
B. Consider the following list exam and write python built in function for the following
questions
Exam=[‘hindi’,’english’,’maths’,’science’]
1. To insert subject ‘computer science’ as last element.
Ans. Exam.append(‘computer science’)
2. To sort the list in reverse alphabetical order. Ans. L1.sort(reverse = True)
19
MLL Material, Class XII Computer Science, KVS RO Lucknow 20
(A) Write a statement to sort the elements of list prices in ascending order ----------------- Ans.
prices.sort()
(B) Write the statement to find the minimum or smallest element from list ---------------- Ans.
min(prices)
(A) Add the element “Apr” at the last ----------- Ans. L.append(‘Apr’)
(B) Find the index of “Feb” ------- Ans. L.index(“Feb”)
9 Consider the following list exam and write Python statement for the following
questions:
exam=[‘english’,’physics’,’chemistry’,’cs’,’biology’]
i) To insert subject “maths” as last element ----- exam.append(‘maths’)
ii) To display the list in reverse alphabetical order --- L1.reverse()
Common Mistakes committed by students while writing the answer:
To differentiate append() and extend() function.
Gist of the topic: Most commonly used built-in functions and methods of TUPLE
20
MLL Material, Class XII Computer Science, KVS RO Lucknow 21
OUTPUT –(3, 4, 5, 5, 5, 6)
(6, 5, 5, 5, 4, 3)
6 max() t1 = [1, 2, 3, 4, 5, 6]
min() print(max(t1))
sum() print(min(t1))
gives maximum, minimum value if print(sum(t1)
tuple contains same type of
Values. sum() finds sum of OUTPUT – 6
numbers. 1
21
Ans –
Lst = list(subject)
Lst.pop()
2 Identify the invalid python statement from the following:
(A) t=(100) (B) t=tuple() (C) t=(100,) (D) None of these
21
MLL Material, Class XII Computer Science, KVS RO Lucknow 22
Gist of the topic: Most commonly used built-in functions and methods of dictionary
1 dict() d2 = dict()
Empty dictionary. print(d2)
OUTPUT – {}
{'name': 'Sanjeev', 'post': 'PGT', 'sub': 'CSIP'}
{'name': 'Sanjeev', 'post': 'PGT', 'sub': 'CSIP'}
{'name': 'Sanjeev', 'post': 'PGT', 'sub': 'CSIP'}
{'name': 'Sanjeev', 'post': 'PGT', 'sub': 'CSIP'}
{'name': 'Sanjeev', 'post': 'PGT', 'sub': 'CSIP'}
{'name': 'Sanjeev', 'post': 'PGT', 'sub': 'CSIP'}
2 len() lst1 = [1, 2, 3, 4, 5, 6]
counts number of print(len(lst1)) # OUTPUT – 6
elements.
3 keys() trs={"SanjeevKumar":"CS&IP",5:"ComputersSec",
gives all keys in a (1,2):"ComputersPri"}
sequence. print(trs.keys())
print(trs.values())
4 values()
gives all values in a OUTPUT –
sequence. dict_keys(['SanjeevKumar', 5, (1, 2)])
dict_values(['CS&IP', 'ComputersSec', 'ComputersPri'])
22
MLL Material, Class XII Computer Science, KVS RO Lucknow 23
OUTPUT –
{'name': 'Sanjeev', 'post': 'PGT', 'sub': 'CSIP'}
{'name': 'Sanjeev', 'post': 'PGT', 'sub': {1: 'CS', 2: 'IP'},
'mob': 9476785270}
8 sorted() d = {41:'neha', 12: 'saima', 32:'avnit', 24:'ana', 15:'shaji'}
create a new list and l1 = sorted(d)
assign existing dictionary l2 = sorted(d,reverse=True)
keys in Ascending/ print(l1)
Descending Order. print(l2)
OUTPUT –
[12, 15, 24, 32, 41]
[41, 32, 24, 15, 12]
9 clear() trs={'name':"Sanjeev",'post':"PGT",'sub':"CSIP"}
removes all elements trs.clear()
from dictionary. print(trs)
OUTPUT – {}
10 fromkeys() Nd = dict.fromkeys([2,4,6,8], 'sk')
creates a dictionary with print(Nd)
multiple keys and Nd = dict.fromkeys([2,4,6,8])
comman value. print(Nd)
OUTPUT –
{2: 'sk', 4: 'sk', 6: 'sk', 8: 'sk'}
{2: None, 4: None, 6: None, 8: None}
11 copy() s1 = {1:'neha', 2:'saima',3:'avnit',4:'ans'}
creates a shallow copy of s2 = s1.copy()
a dictionary print(s1)
print(s2)
s2[5] = 'sk'
print(s1)
print(s2)
OUTPUT –
{1: 'neha', 2: 'saima', 3: 'avnit', 4: 'ans'}
{1: 'neha', 2: 'saima', 3: 'avnit', 4: 'ans'}
{1: 'neha', 2: 'saima', 3: 'avnit', 4: 'ans'}
{1: 'neha', 2: 'saima', 3: 'avnit', 4: 'ans', 5: 'sk'}
23
MLL Material, Class XII Computer Science, KVS RO Lucknow 24
12 pop() trs={'name':"Sanjeev",'post':"PGT",'sub':"CSIP"}
remove key:value from print(trs.pop('sub'))
the dictionary using key print(trs)
and returns its value. If print(trs.pop('sub',"Not Found"))
key is missing gives
KeyError. OUTPUT –
CSIP
{'name': 'Sanjeev', 'post': 'PGT'}
Not Found
13 popitem() s1 = {1:'neha', 2:'saima',3:'avnit',4:'ans'}
pop and returns print(s1.popitem())
(key,value )
KeyError if dictionary id OUTPUT-
empty. (4, 'ans')
14 setdefault() s1 = {1:'neha', 2:'saima',3:'avnit',4:'ans'}
insert new key:value if v = s1.setdefault(5,'sk')
not exists and value, if key print(s1)
exists than gives its value. print(v)
v = s1.setdefault(5,'sk')
print(s1)
print(v)
OUTPUT –
24
MLL Material, Class XII Computer Science, KVS RO Lucknow 25
2 If one_dict is a dictionary as defined below, then which of the following statements will raise an exception
one_dict = {'shoes': 1000, 'bag': 1200, 'specs': 500}
(a) one_dict.get('specs')
(b) print(one_dict['shooes'])
(c ) k=one_dict.keys()
(d ) print(str(one_dict))
ANS - Students.pop(‘NISHA’)
6
Ans – dict1.update(dict2)
Dict1.clear()
Gist of the topic: Most commonly used built-in functions and methods of math and statistics module
Python Standard Library provides math module to perform math related operations which works on
Numbers except Complex Numbers. Don’t forget to import math module.
OUTPUT –
import math
num1 = int(input("Input Integer Number1 = ")) Input Integer Number1 = 5
num2 = int(input("Input Integer Number2 = ")) Input Integer Number2 = 3
num3 = float(input("Input Real Number3 = ")) Input Real Number3 = 2.4
res = math.ceil(num3)
25
MLL Material, Class XII Computer Science, KVS RO Lucknow 26
res = math.sqrt(num1)
print("Square root of ",str(num1)," is ",res) Square root of 5 is 2.23606797749979
res = math.exp(num1)
print("Natural Log of e ^ ",str(num1)," is ",res) Natural Log of e ^ 5 is 148.4131591025
res = math.fabs(num1)
print("Absolute Value of ",str(num1)," is ",res) Absolute Value of 5 is 5.0
res = math.floor(num3)
print("Floor Value of ",str(num3)," is ",res) Floor Value of 2.4 is 2
26
MLL Material, Class XII Computer Science, KVS RO Lucknow 27
27
MLL Material, Class XII Computer Science, KVS RO Lucknow 28
print(a)
Ans:
Output: 30 60
10
Start
Key Points:
a = 10
The convert function has a default
value for the parameter b (20), but it's
Call function convert(30) overridden by the argument 30 during
(Inside convert function) the function call.
The assignment a = 30 within the
a = 30 function creates a local variable a that
is only accessible within the function's
scope. It does not modify the global
c=a+b variable a
c = 30 + 30
Print(a, c)
Print(30, 60)
28
MLL Material, Class XII Computer Science, KVS RO Lucknow 29
Calls the printMe function with q=a (which is 10) and r=b (which is 5).
p = 5 + 10**3 = 5 + 1000 = 1005
Prints 1005
o printMe(r=4,q=2): # Keyword Arguments
Calls the printMe function with r=4 and q=2 (using keyword arguments).
p = 4 + 2**3 = 4 + 8 = 12
Prints 12
6. Write the output of following code fragment:
p = 25
def sum(q, r=3):
global p
p = r + q**2
print(p, end=' ')
a=6
b=4
sum(a, b)
sum(r=5, q=1)
Output
40 6
Explanation:
1. Initialization:
o p = 25 initializes a global variable p with a value of 25.
2. Function Definition:
o def sum(q, r=3): defines a function named sum that takes two arguments:
q: Required argument.
r: Optional argument with a default value of 3.
o global p: This statement declares that the variable p used within the function refers to the
global variable p defined outside the function.
o p = r + q**2: Calculates the value of p as r plus the square of q and assigns it to the global
variable p.
o print(p, end=' '): Prints the updated value of p followed by a space.
3. Variable Assignments:
o a = 6 assigns the value 6 to the variable a.
o b = 4 assigns the value 4 to the variable b.
4. First Function Call (sum(a, b)):
o Calls the sum function with q=6 and r=4.
o Inside the function:
p = 4 + 6**2 = 4 + 36 = 40 (global p is now 40)
print(p, end=' '): Prints "40 "
5. Second Function Call (sum(r=5, q=1)):
o Calls the sum function with r=5 and q=1 (using keyword arguments).
o Inside the function:
p = 5 + 1**2 = 5 + 1 = 6 (global p is now 6)
print(p, end=' '): Prints "6 "
29
MLL Material, Class XII Computer Science, KVS RO Lucknow 30
Ans: Option –A
Explanation:
Keyword Arguments: In Python, keyword arguments allow you to pass values to a function by
explicitly specifying the parameter names.
How they work:
o Instead of relying on the order of arguments, you use the keyword (parameter name)
followed by the value when calling the function.
o This makes the code more readable and flexible, especially when dealing with functions
that have many parameters.
Common Mistakes:
Certainly, here are some common mistakes students make when solving Python code involving functions,
particularly with examples like the one provided:
1. Scope Issues:
30
MLL Material, Class XII Computer Science, KVS RO Lucknow 31
31
MLL Material, Class XII Computer Science, KVS RO Lucknow 32
Name of unit-Computational Thinking-II Name of chapter- Data File Handling (text files & csv files), stack
(push and pop)
Fill in the blanks
1. A collection of bytes stored in computer’s secondary memory is known as _______.
2. ___________ is a process of storing data into files and allows to performs various tasks such as read, write,
append, search and modify in files.
3. The transfer of data from program to memory (RAM) to permanent storage device (hard disk) and vice versa
are known as __________.
4. A _______ is a file that stores data in a specific format on secondary storage devices.
5. In ___________ files each line terminates with EOL or ‘\n’ or carriage return, or ‘\r\n’.
6. To open file data.txt for reading, open function will be written as f = _______.
7. To open file data.txt for writing, open function will be written as f = ________.
8. In f=open(“data.txt”,”w”), f refers to ________.
9. To close file in a program _______ function is used.
10. A __________ function reads first 15 characters of file.
11. A _________ function reads most n bytes and returns the read bytes in the form of a string.
12. A _________ function reads all lines from the file.
13. A _______ function requires a string (File_Path) as parameter to write in the file.
14. A _____ function requires a sequence of lines, lists, tuples etc. to write data into file.
15. To add data into an existing file ________ mode is used.
16. A _________ function is used to write contents of buffer onto storage.
17. A text file stores data in _________ or _________ form.
18. A ___________ is plain text file which contains list of data in tabular form.
19. You can create a file using _________ function in python.
20. A __________ symbol is used to perform reading as well as writing on files in python.
ANSWERS
1. File
2. File Handling
3. I/O Operations
4. Data file
5. Text File
6. open(“data.txt”,”r”)
7. open(“data.txt”,”w”)
8. File handle or File Object
9. close
10. read(15)
11. readline()
12. readlines()
13. write()
14. writelines()
15. append
16. flush()
17. ASCII, UNICODE
18. CSV
19. open()
20. +
32
MLL Material, Class XII Computer Science, KVS RO Lucknow 33
Text file
Text files in Python are widely used for storing and processing data. Python provides built-in functionality to work with
text files using file I/O operations. Here’s a quick overview of key concepts and operations:
Opening and Closing Files : Use the open() function to open a file. Files can be opened in different modes:
Always close the file after operations using file.close() or a with statement to handle files automatically.
Writing to Files
Appending to Files : Use 'a' mode to append new data without overwriting the file. Eg.
Tips
21. . Write a function count_lines() to count and display the total number of lines from the file. Consider above
file – friends.txt.
33
MLL Material, Class XII Computer Science, KVS RO Lucknow 34
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
print("no. of lines:",cnt)
f.close()
4. Write a function display_oddLines() to display odd number lines from the text file. Consider above file –
friends.txt.
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
5. Write a function cust_data() to ask user to enter their names and age to store data in customer.txt file.
def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("customer.txt","w")
f.write(data)
f.close()
6. Write a program to count the numbers of word in text F1.txt file.
CSV file
(Comma Separated Values file) is a type of plain text file that uses specific structuring to arrange tabular data. Because
it’s a plain text file, it can contain only actual text data—in other words, printable ASCII or Unicode characters. The
structure of a CSV file is given away by its name. Normally, CSV files use a comma to separate each specific data
value.
CSV Advantages
CSV is human readable and easy to edit manually
CSV format is common for data interchange.
CSV is faster to handle
CSV is smaller in size
CSV Disadvantages
CSV allows moving most basic data only.
There is no distinction between text and numeric values
34
MLL Material, Class XII Computer Science, KVS RO Lucknow 35
The CSV file format is not fully standardized. The basic idea of separating fields with a comma is clear, but that idea gets
complicated when the field data may also contain commas or even embedded line-breaks. CSV implementations may
not handle such field data, or they may use quotation marks to surround the field. Quotation does not solve everything:
some fields may need embedded quotation marks, so a CSV implementation may include escape characters or escape
sequences.
STACK
1. What is data structure and why do we need it?
Ans: Data structure is a particular way of storing and organizing information in a computer so that it can be retrieved
and used most productively. Different kinds of data structures are meant for different kinds of applications, and some
are highly specialized to specific tasks.
2. what is a stack ? what basic operation can be performed on them?
Ans: A stack is a collection of objects that supports fast last-in, first-out (LIFO) semantics for inserts and deletes.
Basic operation are:
a) Push – insertion of element
b) Pop – deletion of an element
c) Peek- viewing topmost element without removing
d) Display- view all the element
3. Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book
and delete a Book from a list of Book titles, considering them to act as push and pop
operations of the Stack data structure.
def PushOn(Book):
Answers-
a=input(“enter book title :”)
Book.append(a)
def Pop(Book):
if (Book = =[ ]):
print(“Stack empty”)
else:
print(“Deleted element :”)
Book.pop()
35
MLL Material, Class XII Computer Science, KVS RO Lucknow 36
Networking – A computer network is a collection of interconnected computers and other devices which are able to
communicate with each other. Also defined as - collection of hardware components and computers interconnected by
communication channels that allow sharing of resources and information.
Advantages of Networking :-
1. Resource Sharing (Printer, DVD, etc.)
2. Cost Saving
3. Collaborative user interaction
4. Time savings
5. Increased storage
INTERNET – network of networks (super network)
GATEWAY - is a device used to connect different type of networks and perform the necessary translation so that the
connected networks can communicate properly.
TCP – Transmission control protocol
- Divide file/message into packets
- Reassemble the packets at receiving end
IP – Internet Protocol
- Provide address to each packet so that packet is routed to its proper destination
NIU(OR NIC) NETWORK INTERFACE UNIT(CARD) is a device that enables a computer to connect a network and
communicate. Now a days, NIC is integral part of motherboard. Unique physical address assigned to NIC by manufacturer
is known as MAC(Media Access Control) address and it cannot be changed by user whereas IP address can be changed by
user.
SWITCHING
CIRCUIT SWITCHING –
1. Complete physical connection between two computer is established and then data transfer starts. Like in
Telephone call.
PACKET SWITCHING
1. In message switching there is no limit on block size, where as in packet switching there is tight limit on block
size.
2. It stores data in Primary memory
3. It is faster than Message switching
TRANSMISSION MEDIA
A. GUIDED MEDIA (WIRED)
1. TWISTER PAIR CABLE
a. Wires come in pairs
b. The pairs of wires are twisted around each other. Twisting reduce cross-talk
c. Advantage
i. Easy to install and maintain
ii. Flexible
iii. Can be easily connected
Types of Twisted Pair cable
d. UTP (unshielded twisted pair) – as name suggest these are not shielded.
Main characteristics of UTP cable –
i. Low cost
ii. Suitable for small network
iii. Carry data up to length of 100 m
2. SHIELDED TWISTED PAIR(STP)
Characteristics –
36
MLL Material, Class XII Computer Science, KVS RO Lucknow 37
37
MLL Material, Class XII Computer Science, KVS RO Lucknow 38
2. BAUD – unit of measurement for the information carrying capacity of communication channel. Synonym
– bps (bits per second) Small ‘b’ means bits Capital ‘B’ means Bytes Kbps, Mbps
3. BANDWIDTH –
Difference between highest and lowest frequencies of a transmission channel. Bandwidth speed in
digital system is bits per second. In analog system it is measured in Hertz like KHz(Kilo hertz), MHz.
TYPE OF NETWORKING
1. LAN(Local area network) –
Network of computing/communication devices in a room, building or campus
cover area of few kilometer radius(approx. 10 KM)
can be setup using wired or wireless media
managed by single person or organization
2. MAN (metropolitan area network)–
Network of computing/communicating devices within a city.
Cover an area of few kilometers to few hundred kilometers radius
Network of schools, banks, government offices within a city are example of MAN.
It is typically formed by interconnected number of LANs
3. WAN –
Network of computing/communication devices crossing the limits of city, country, or continent.
cover area of over hundreds of kilometer radius
Network of ATMs, BANKs, National or International organization offices spread over a country,
continent are example of WAN.
It is usually formed by interconnecting LANs, MANs or may be other WANs.
Best example of WAN is internet
4. PAN –
Network of communicating devices(computer, phone, MP3 etc.)
Cover area of few meters radius
When we transfer songs from one cell phone to another we setup a PAN of two phones
Can be setup using guided or unguided media
NETWORK TOPOLOGIES (PHYSICAL ARRANGEMENT OF NODES IN NETWORK)
1. POINT TO POINT – Transmitter and receiver, transmitter will transmit to one receiver and receiver will receive
from only one transmitter.
2. STAR TOPOLOGY –
1. Each node is directly connected to hub/switch
2. If any node wants to send information to any other node it sends signal to the hub/switch
Characteristics
1. it require more cable length as compared to bus topology
2. easy to install
3. more efficient than bus topology
4. fault diagnosis is easy in star topology
5. failure of hub/switch leads to a failure of entire network
6. easy to expand depending on specification of hub/switch
3. BUS Topology
1. All nodes are connected to main cable called backbone.
2. If any node has to send some information to any other node, it sends the signal to backbone. The
signal travels through the entire length of backbone and is received by the node for which it is
intended.
3. A small device called terminator is attached at each end of backbone, when signal reaches to end of
backbone it is absorbed by terminator and backbone gets free to carry another signal.
Characteristics
1. Easy to install
2. Requires less cable length
38
MLL Material, Class XII Computer Science, KVS RO Lucknow 39
3. Cost effective
4. Backbone failure mean entire network failure
5. Fault diagnosis is difficult
6. Only one node can transmit data at a time
4. TREE TOPOLOGY –
1. Combination of bus and star topologies.
2. Combines multiple star topologies together like a bus.
3. Used in expanding network
Characteristics
easy way of network expansion
even if one network fails, the other network remain connected and working
NETWORK DEVICES
MODEM (MODULATOR-DEMODULATOR) : It convert analog signal to digital signal and vice-versa.
RJ-45(REGISTERED JACK) : Used to connect computers to Local area network. Used with UTP/STP (Ethernet)
cables
ETHERNET: Uses bus or star topologies and can support data transfer up to 10 Mbps. Ethernet card also known
as NIC.
HUB: is an electronic device that connect several nodes to form a network and redirect the received information
to all the connected nodes in a broadcast mode.
i. Active Hub – amplify signals as it moves from one device to another. It is used like repeaters.
ii. Passive Hub – pass signals without amplifying
SWITCHis an intelligent device that connect several nodes to form a network and redirect the received information
only to the intended node(s)
REPEATER A device that amplifies a signal being transmitted on network. In long network signals becomes weak,
to regenerate or amplify signals repeaters are used.
BRIDGE Allows connecting two similar type of networks or protocols
ROUTER A device work like bridge but can handle different protocols. It can link Ethernet to mainframe.
GATEWAY Allow connecting dissimilar networks. It expands the functionality of routers by performing data
translation and protocol conversion.
GOOD NETWORK DESIGN (80-20) means 80 percent of traffic on given network segment is local and not more than 20
percent of the network traffic should need to move across a backbone
NETWORK PROTOCOLS
1. HTTP: Hyper Text Transfer Protocol, is the protocol that is used for transferring hypertext files on the
World Wide Web.
2. FTP: File Transfer Protocol, is used for transferring files from one system to another on the Internet.
3. PPP: Point-to-Point Protocol, is used for communication between two computers using a serial interface.
4. SMTP: Simple Mail Transfer Protocol, allows transmission of email over the Internet.
5. TCP: Transmission Control Protocol, breaks the data into packets that the network can handle efficiently.
6. IP: Internet Protocol, gives distinct address (called IP address) to each data packet.
7. POP3: Post Office Protocol 3, receives and holds email for an individual until they pick it up.
8. HTTPS: Hypertext Transfer Protocol Secure, is an extension of the HTTP. It uses encryption for secure
communication over a computer network, and is widely used on the Internet.
9. TELNET: A protocol for creating a connection with a remote machine.
10. VoIP: VOIP stands for voice over internet protocol. It enables the transfer of voice using packet switched
network rather than using public switched telephone network.
INTRODUCTION TO WEB SERVICES
1. WWW: World Wide Web, can be defined as a hypertext information retrieval system on the Internet. Tim
Berners -Lee is the inventor of WWW. WWW is the universe of the information available on the Internet.
39
MLL Material, Class XII Computer Science, KVS RO Lucknow 40
HTML XML
XML stands for Extensible Markup
HTML stands for Hyper Text Markup Language.
Language.
HTML is static in nature. XML is dynamic in nature.
It was developed by Worldwide Web
It was developed by WHATWG.
Consortium.
HTML is not Case sensitive. XML is Case sensitive.
HTML tags are predefined tags. XML tags are user-defined tags.
There are limited number of tags in HTML. XML tags are extensible.
3. Domain names: A domain name is the sequence of letters and or numbers separated by one or more
period (“.”). Domain names serve to identify Internet resources, such as computers, networks, and
services.
4. URL: A Uniform Resource Locator (URL), informally known as an address on the Web, is a reference to
a resource that specifies its location on a computer network and a mechanism for retrieving it.
5. Web browser: Web browser is software program to navigate the web pages on the internet. A bowser
interprets the coding language of the web page and displays it in graphic form.
6. Web servers: A Web server is a computer or a group of computers that stores web pages on the Internet.
It works on client/server model. It delivers the requested web page to web browser.
7. Web hosting: Web hosting is the process of uploading/saving the web content on a web server to make it
available on WWW.
Question and Answers:
40
MLL Material, Class XII Computer Science, KVS RO Lucknow 41
6 Identify the cable which consists of an inner copper core and a second conducting outer sheath:
(i) Twisted Pair(ii) Co-axial (iii) Fiber Optical (iv) Shielded Twisted Pair
Ans. Co-axial
7 In fiber optic transmission, data is travelled in the form of:
(i) Light (ii) Radio link (iii) Microwave Link (iv) Very low frequency
Ans. Light
8 Out of the following, Which transmission media has the highest transmission speed in a network?
(i) Twisted Pair Cable (ii) Co-axial Cable (iii) Fiber Optical (iv) Electrical Cable
Ans. Fiber Optical
9 Which of the following devices modulates digital signals into analog signals that can be sent over traditional
telephone lines?
(i) Router (ii) Gateway (iii) Bridge (iv) Modem
Ans. Modem
10 What is the name of earliest form of Internet? Also expand it
Ans. ARPANet :Advanced Research Project Agency Network
11 A Local telephone line network is an example of ___________ network
(i) Packet Switched (ii) Line Switched (iii) Circuit Switched (iv) Bit switched
Ans. Circuit Switched
12 The required resources for communication between end systems are reserved for the duration of the session
between end systems in ________ method
Ans. Circuit Switching
13 In which type of Switching techniques, the resources are allocated on demand?
Ans. Packet Switching
14 What is Bandwidth? What is the measuring unit of Bandwidth in term of range of frequencies a channel can
pass?
Ans. Bandwidth: Data transfer rates that can be supported by a network is called its bandwidth.
Bandwidth can be measured in 2 ways:
(i) In Hertz : KHz, MHz, GHz
(ii) In Bits per second : Mbps, Gpbs
15 What are the different types of Transmission Media? Give example of each.
Ans. There are 2 types of Transmission media:
(i) Wired : Twisted pair cable, co-axial cable, fiber optical cable
(ii) Wireless : Radio waves, microwaves, infrared, satellite
16 What is the difference between Radio wave transmission and Microwave transmission?
Ans. Radio waves Microwaves
It travels in Omni-directional It travels in straight line
It can penetrate solid objects It cannot penetrate solid objects
Sender and receiver antenna need not to be properly Sender and receiver antenna must be proper aligned
aligned as it is line-of-sight transmission
17 Which wireless transmission medium is used for controlling our TV, AC with Remote?
Ans. Infrared
18 Which of the transmission is suitable for the transferring data from one place to anywhere in the world?
Ans. Satellite
19 Out of the following guided media, which is not susceptible to external interference?
(i) Twisted Pair (ii) Co-axial Cable (iii) Fiber Optical (iv) Electric Wire
Ans. Fiber Optical
20 Which connector is used connect Ethernet Cable to LAN Card?
Ans. RJ-45 (Registered jack)
21 What is NIC? Give the name of unique number assigned to each NIC.
Ans. Network Interface Card. The unique number assigned to each NIC is MAC Address (Media access control)
41
MLL Material, Class XII Computer Science, KVS RO Lucknow 42
22 Which device is used for sorting and distribution of data packet to their destination based on their IP Address?
Ans. Router
23 Why Switch is known as Intelligent Hub?
Ans. Switch filters the incoming packets and finds the destination node from the MAC table. It transmit data only to
intended node.
24 Which device is used to connect network of different protocols so that they can communicate properly?
Ans. Gateway
25 Supacell ltd is planning to setup its centre in Delhi with four specialized blocks for Medicine, Management, Law
courses along with an Admission block in separate buildings. The physical distances between these blocks and
no. of computers to be installed in these block are given below. You as a network expert have to answer the
queries raised by their board of directors as given in (i) to (v).
Blocks Dist(mtrs) Block No. of Computers
Admin to Management 60 Admin 150
Admin to Medicine 40 Management 70
Admin to Law 60 Medicine 20
Law to Medicine 40 Law 50
Medicine to Management 50
(i) Suggest the most suitable location to install the server of this institution to get efficient connectivity.
(ii) Suggest the location for the following device to be installed
(a) Modem (b) Switch
(iii) Suggest by drawing the best cable layout for effective network connectivity of the blocks having server with
all other blocks.
(iv) Suggest the most suitable wired medium for efficiently connecting each computer installed in every building
out of the following network cables:
(a) Coaxial Cable (b) Ethernet Cable (c) Fiber Optical (d) Telephone Cable
(v) Is there any requirement of repeater in the cable layout? Why / Why not?
SOME MORE QUESTIONS
1. Ethernet card is also known as : (A) LIC (B) MIC (C) NIC (D) OIC
Ans. (C) NIC
2. Give one difference between HTTP and FTP.
Ans.
HTML FTP
HTML stands for HyperText Markup Language. It is File Transfer Protocol, is used for transferring files
the standard language used to create and from one system to another on the Internet.
structure content on the web.
42
MLL Material, Class XII Computer Science, KVS RO Lucknow 43
43
MLL Material, Class XII Computer Science, KVS RO Lucknow 44
KEYS: In a relation each record should be unique i.e. no two records can be identical in a database.
A key attribute identifies the record and must have unique values
Keys are of four types:
1. Primary Key
2. Candidate Key
3. Alternate Key
4. Foreign Key
44
MLL Material, Class XII Computer Science, KVS RO Lucknow 45
Primary Key: A primary key uniquely identifies a record in a table. A primary key always have distinct values and also
cannot have NULL values. In a table we can only have one primary key. Eg. in the above table EmpNo is the primary key.
Candidate Key: All the attributes in a table which have the capability to become a primary key are referred to as a
candidate key. i.e., a column that has unique value for each row in the relation and that can not be NULL. Eg. in the above
table EmpNo and Ename are the attributes which have the capability to become the primary key so, empno and ename
are the candidate keys
Alternate Key: The candidate keys which is not primary key are called alternate keys.
Eg. if empno is the primary key then the remaining candidate key ename is the alternate key.
Foreign Key: A foreign key is a non key attribute whose values are derived from the primary key of another table. It is
basically used to set the relationship among two tables.
From above tables, we can observe that the DeptNo column of table Employee is deriving its value from DeptNo column
of table Department. So, we can say that the DeptNo of table Employee is a foreign key whose value are derived from
primary key column DeptNo of table Department.
Structured Query Language (SQL): It is a programming language for storing and processing information in a relational
database.
SQL Commands: SQL commands are instructions to communicate with the database. It is also used to perform specific
tasks like creating tables, adding records, modifying data, removing rows, dropping tables etc.
45
MLL Material, Class XII Computer Science, KVS RO Lucknow 46
DATA TYPES: Data types are means to identify the type of data and associated operations for handling it.
MySQL data types are divided into following categories:
CHAR(size) A FIXED length string its size can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string, its size can be can be from 0 to 65535
INT(size)/ Integer Number without decimal point. Example int(11) or integer
FLOAT(size, d) / A floating point number. The total number of digits is specified in size. The number of digits
Decimal after the decimal point is specified in the d parameter. Example float(10,2). Example
3455738.50
DATE A date. Format: YYYY-MM-DD. Example DOB date ‘2008-11-28’
46
MLL Material, Class XII Computer Science, KVS RO Lucknow 47
47
MLL Material, Class XII Computer Science, KVS RO Lucknow 48
48
MLL Material, Class XII Computer Science, KVS RO Lucknow 49
49
MLL Material, Class XII Computer Science, KVS RO Lucknow 50
DROP REMARKS;
40 (i) Open source software i.e. downloaded free of cost (ii) provides security to data (iii)
easy to use
PREPARED BY: MOHAMMAD HASHIM, PGT(CS), PM SHRI K V NO 2 OCF SHAHJAHANPUR, LUCKNOW
REGION
50
MLL Material, Class XII Computer Science, KVS RO Lucknow 51
Aggregate Functions: Aggregate functions are used to perform calculations on a set of values and
return a single value. The most common aggregate functions in SQL are:
1. MAX: Returns the maximum value in a set of values.
2. MIN: Returns the minimum value in a set of values.
3. AVG: Returns the average value in a set of values.
4. SUM: Returns the sum of all values in a set of values.
5. COUNT: Returns the number of rows in a table or the number of non-NULL values in a
column.
Example: SELECT MAX(salary) AS max_salary FROM employees;
This query returns the maximum salary in the employees table.
GROUP BY Command:
The GROUP BY command is used to group rows in a table based on one or more columns.
The GROUP BY command is often used with aggregate functions to perform calculations
on groups of rows.
Syntax: SELECT column1, column2, ... FROM table_name GROUP BY column1, column2,
...;
Example: SELECT department, AVG(salary) AS avg_salary FROM employees
GROUP BY department;
This query groups the rows in the employees table by the department column and
calculates the average salary for each department.
Using Aggregate Functions with GROUP BY:
When using aggregate functions with the GROUP BY command, the aggregate function is
applied to each group of rows separately.
Example: SELECT department, MAX(salary) AS max_salary, MIN(salary) AS min_salary
FROM employees GROUP BY department;
51
MLL Material, Class XII Computer Science, KVS RO Lucknow 52
This query groups the rows in the employees table by the department column and calculates the
maximum and minimum salary for each department.
Questions and Answers:
1. Consider the table ORDERS as given below
(IV) MAX(Price)
-----------
12000
2. Consider the tables PRODUCT and BRAND given below:
Table: PRODUCT
52
MLL Material, Class XII Computer Science, KVS RO Lucknow 53
Table: BRAND
BID BName
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove
Answer:
(i) SELECT PName, BName FROM PRODUCT P, BRAND B WHERE P.BID=B.BID;
(ii) DESC PRODUCT;
(iii) SELECT BName, AVG(Rating) FROM PRODUCT P, BRAND B WHERE P.BID=B.BID GROUP BY
BName HAVING BName='Medimix' OR BName='Dove';
(iv) SELECT PName, UPrice, Rating FROM PRODUCT ORDER BY Rating DESC;
Common Mistakes committed by students while writing the answer:
1. Incorrect table or column names: Make sure to use the correct table and column names,
including the correct spelling and case.
2. Insufficient or incorrect WHERE clause: Omitting or incorrectly specifying the WHERE clause
can lead to unintended data modifications or deletions.
3. Incorrect data types: Ensure that the data types of the columns match the data types of the
values being inserted, updated, or deleted.
4. Confusion over use of where and having:
a. Where filters individual rows, while HAVING filters groups of rows.
b. WHERE is applied before GROUP BY, while HAVING is applied after GROUP BY.
Example—
SELECT department, salary FROM employees
WHERE job_title = 'Manager'
GROUP BY department
HAVING count(*) > 2;
In this example, the WHERE clause filters out non-manager employees, and the HAVING clause
filters the departments based on number of employees ( having more than 2 employee)
53