0% found this document useful (0 votes)
170 views53 pages

SSM Xii Computer Science

Hhg

Uploaded by

incredibleman653
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
170 views53 pages

SSM Xii Computer Science

Hhg

Uploaded by

incredibleman653
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

केंद्रीय विद्यालय संगठन लखनऊ संभाग

KENDRIYA VIDYALAYA SANGATHAN LUCKNOW REGION

बोर्ड कक्षाओं के वलए पूरक अध्ययन सामग्री


SUPPLEMENTARY STUDY MATERIAL FOR
BOARD CLASSES
कक्षा/CLASS : XII
विषय/SUBJECT: कंप्यूटर विज्ञान/COMPUTER SCIENCE (083)

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

S. Unit Topic Page


No.
1 Computational Thinking-II Revision of XI [Python basic, Data 4-12
Types, Operators, Expression Solving,
Finding Errors]
2 Revision of XI [Most commonly used 13-26
built-in functions and methods of
string, list, tuple and dictionary, use of
math and statistics functions]
3 Functions [Arguments and 27-31
Parameters, local and global variable]
4 Data File Handling (text files & csv 32-35
files), stack (push and pop)
5 Computer Network Computer Network-I 36-43
6 Computer Network – II
7 Database Management DBMS Concepts, Database 44-53
System Commands, DDL Commands
8 DML Commands up to group by

3
MLL Material, Class XII Computer Science, KVS RO Lucknow 4

Name of Unit: Name of Chapter:


Computational Thinking-II Python Basics and Fundamentals
Topic: Revision of XI [Python basic, Data Types, Operators, Expression Solving, Finding Errors]

Gist of the topic:

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:

result = 10 + 2 * 3 # Multiplication has higher precedence than addition


print(result) # Output: 16
2. Parentheses Override Precedence: Parentheses () can be used to override the default precedence to
explicitly specify the order of evaluation.
Example:
result = (10 + 2) * 3 # Parentheses change the evaluation order
print(result) # Output: 36
3. Left-to-Right Associativity: Most operators are left-associative, meaning they are evaluated from left to
right.
Example:
result = 10 - 5 - 2 # Evaluated as (10 - 5) - 2
print(result) # Output: 3
4. Right-to-Left Associativity : Some operators (like ** for exponentiation) are right-associative, meaning
they are evaluated from right to left.
Example:
result = 2 * 3 * 2 # Evaluated as 2 * (3 * 2)
print(result) # Output: 512

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,

 Reading the Code Carefully


 Look for Syntax Errors: These are mistakes in the structure of your code, such as missing colons,
parentheses, or indentation errors.
 Check Logical Errors: These occur when the code runs but doesn’t produce the desired result.
Example:

 Common Errors to Look For

• Syntax Errors: Missing colons, parentheses, or indentation issues.


• Name Errors: Using undefined variables or functions.
Eg. print(my_var) # NameError: name 'my_var' is not defined
• Type Errors: Performing unsupported operations between types.
print(5 + "5") # TypeError: unsupported operand type(s)
• Value Errors: Using invalid values for a function.
int("abc") # ValueError: invalid literal for int()
• Index Errors: Accessing out-of-range list indices.
my_list = [1, 2, 3]
print(my_list[5]) # IndexError: list index out of range.

Types of Errors:

Syntax Errors: Runtime Errors: Logical Errors:


Occur when the code violates Occur while the program is Occur when the code runs
Python's syntax rules. running, often due to invalid without crashing but produces
Example: operations. incorrect results.

6
MLL Material, Class XII Computer Science, KVS RO Lucknow 7

Example: Example: Incorrect calculation


print "Hello, World!" # Missing due to a wrong formula.
parentheses result = 10 / 0 # Division by
zero total = 10 * 2 # Should be
addition instead of
multiplication

Questions and Answers:


Python Basics and Data types:
 Q: What is Python?
A: Python is a high-level, interpreted programming language known for its simplicity and readability. It
supports multiple programming paradigms, including procedural, object-oriented, and functional
programming.
 Q: Who developed Python and when was it first released?
A: Python was developed by Guido van Rossum and was first released in 1991.
 Q: Write a simple Python program to display "Hello, World!" on the screen.
A:print("Hello, World!")
 Q: What is the use of the print() function in Python?
A: The print() function is used to display output to the console.
 Q: How do you write a multi-line string in Python?
A: Multi-line strings can be written using triple quotes (''' or """).
Example: my_string = """This is a
multi-line
string."""
 Q: How do you add comments in Python code?
A: Single-line comments in Python are added using the # symbol. Multi-line comments can be added
using triple quotes (''' or """).
 Q: Why are comments important in a Python program?
A: Comments are important because they help explain the code to others and make it easier to
understand and maintain.
 Q: What are variables in Python? How do you declare them?
A: Variables are used to store data in memory. You can declare a variable by assigning a value to it.
Example: x = 10
y = "Hello"
 Q: What are the different data types available in Python?
A: Common data types in Python include integers, floating-point numbers, strings, lists, tuples,
dictionaries, and sets.
 Q: What is a tuple in Python? How is it different from a list?
A: A tuple is an ordered, immutable collection of elements. Unlike lists, tuples cannot be modified after
creation.
Example: my_tuple = (1, 2, 3)
 Q: How do you take input from the user in Python?
A: You can use the input() function to take input from the user.
Example: name = input("Enter your name: ")
print("Hello, " + name)
 Q: How can you ensure that the input taken from the user is of a specific data type?
A: You can use type conversion functions like int(), float(), or str() to ensure that the input is of a specific
data type.
 Q: What are the different types of numeric data types in Python?

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

print("Cleared list:", my_list) # Output: []


 Q: What is a tuple in Python?
A: A tuple is an ordered, immutable collection of elements enclosed in parentheses (()). Example:
my_tuple = (1, 2, 3)
 Q: How do you convert a list to a tuple in Python?
A: You can use the tuple() function. Example:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print("Converted tuple:", my_tuple) # Output: (1, 2, 3)
 Q: What is a dictionary in Python?
A: A dictionary is an unordered, mutable collection of key-value pairs enclosed in curly braces ({}).
Example: my_dict = {"name": "Alice", "age": 25}
 Q: Write a Python program to access values in a dictionary using keys.
A: my_dict = {"name": "Alice", "age": 25}
name = my_dict["name"]
print("Name:", name) # Output: Alice
 Q: How do you add a new key-value pair to a dictionary?
A: You can add a new key-value pair by assigning a value to a new key. Example:
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "New York"
print("Updated dictionary:", my_dict)
# Output: {"name": "Alice", "age": 25, "city": "New York"}
 Q: Write a Python program to remove a key-value pair from a dictionary.
A: my_dict = {"name": "Alice", "age": 25, "city": "New York"}
my_dict.pop("age")
print("Updated dictionary:", my_dict) # Output: {"name": "Alice", "city": "New York"}
 Q: What is type conversion in Python?
A: Type conversion, or typecasting, is the process of converting a value from one data type to another.
Python provides built-in functions for type conversion.
Operators:
 Q: What is the difference between / and // operators in Python?
A: The / operator performs floating-point division, while the // operator performs floor division, which
rounds down the result to the nearest integer.
 Q: Write a Python program to evaluate the expression: 3 + 5 * 2 - 8 / 4.
A: The result is 2, as 10 % 4 gives the remainder of the division of 10 by 4.
 Q: What is the result of the expression False and True?
A: The result is False.
1. Q: What will be the value of x after executing the following code?
x = 10
x += 5
x -= 3
A: The value of x will be 12 (10 + 5 - 3).
Expression Solving:
Q. Solve the following expression: 3 + 5 * 2 - 8 / 4.
A. According to the order of operations (PEMDAS/BODMAS), the expression should be evaluated as
follows:
 Multiplication and division first: 5∗2=105 * 2 = 10 8/4=28 / 4 = 2
 Then addition and subtraction: 3+10−2=113 + 10 - 2 = 11
 The final result is: 11
Finding errors-
Q. Identify the error in the following Python code:

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

Common Mistakes committed by students while writing the answers:


Python Basics-

 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

result = 3 + (5 * 2) - (8 / 4) # Correct order: Multiplication and division first, then addition


and subtraction
 Misusing Parentheses:
o Mistake: Misplacing or forgetting parentheses to group operations correctly.
o Example:
result = (3 + 5) * 2 - 8 / 4 # Incorrectly grouped operations
o Correction:
result = 3 + (5 * 2) - (8 / 4) # Correct grouping of operations
 Assuming Associativity Incorrectly:
o Mistake: Incorrectly assuming left-to-right or right-to-left associativity.
o Example:
result = 2 ** 3 ** 2 # Incorrect if assuming left-to-right associativity
o Correction:
result = 2 ** (3 ** 2) # Correct
Finding Errors:
 Improper Use of Indentation:
o Mistake: Failing to use proper indentation, leading to IndentationError.
o Solution: Ensure consistent use of spaces or tabs for indentation.
 Mismatched Parentheses, Brackets, or Braces:
o Mistake: Forgetting to close parentheses (), brackets [], or braces {}, causing syntax errors.
o Solution: Always check that all opening symbols have corresponding closing symbols.
 Division by Zero:
o Mistake: Performing division or modulus operations with zero, causing ZeroDivisionError.
o Solution: Add checks to prevent division or modulus by zero.
 Logical Errors:
o Mistake: Writing code that does not produce the expected output due to incorrect logic.
o Solution: Test the code thoroughly and review the logic to ensure it produces the desired
result.

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

SN Function Prototype Description of Function


1 len(string) It returns the length of its argument string.
>>> len('PPC 2025')
8
2 <string>.capitalize() It returns a copy of the string with its first character
capitalized.
>>>'class XII 2025'.capitalize()
'Class xii 2025'
3 <string>.count(sub[, start[, end]]) It returns the number of occurrences of the substring sub
in string the (or string [start:end] if these arguments are
given). It gives 0 (Zero) if substring is not found.
>>>'CBSE EXAMINATION'.count('E')
2
>>>'CBSE EXAMINATION'.count('E',5,15)
1
4 <string>.find(sub[, start[, end]]) It returns the lowest index in the string where the substring
sub is found within the slice range of start and end. Returns
-1 if sub is not found.
>>> 'CBSE EXAMINATION'.find('E')
3
'CBSE EXAMINATION'.find('E',5,15)
5
5 <string>.index(sub[, start[, end]]) It returns the lowest index where the specified substring is
found otherwise generates exception “ValueError”
>>> 'CBSE EXAMINATION'.index('E',5,15)
5
6 <string>.isalnum() It returns True if the characters in the string are
alphanumeric (alphabets or numbers) and there is at least
one character, False otherwise.
>>> 'CBSE EXAMINATION 2025'.isalnum()
False
>>>'CBSEEXAMINATION2025'.isalnum()
True
7 <string>.isalpha() It returns True if all characters in the string are alphabetic
and there is at least one character, False otherwise.
>>>'CBSEEXAMINATION2025'.isalpha()
False
>>> 'CBSEEXAMINATION'.isalpha()
True
8 <string>.isdigit() It returns True if all the characters in the string are digits.
There must be at least one character, otherwise it returns
False.
>>>'CBSEEXAMINATION2025'.isdigit()
False
>>> '2025'.isdigit()

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

7 What will the output of the following code


S = "text#next"
print(S.strip("t"))
(A) ext#nex (B) ex#nex
(C) text#nex (D) ext#next
8 What will be the output of the following Python code?
s="a@b@c@d"
a=list(s.partition("@"))
print(a)
b=list(s.split("@",3))
print(b)
a) [‘a’,’b’,’c’,’d’] b)[‘a’,’@’,’b’,’@’,’c’,’@’,’d’]
[‘a’,’b’,’c’,’d’] [‘a’,’b’,’c’,’d’]

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

SN Function & Description Example


1 list() l2 = list()
Empty list. print(l2) #OUTPUT – []

s1 = 'sanju'
List from string l5 = list(s1)
print(l5) # OUTPUT – ['s', 'a', 'n', 'j', 'u']

List from tuple t1 = (1, 2, 3, 4, 5)


l6 = list(t1)
print(l6) # OUTPUT – [1, 2, 3, 4, 5]

List from inputted string l7 = list(input("Input List Element - "))


print(l7)

OUTPUT – Input List Element – 12345


['1', '2', '3', '4', '5']

List from Dictionary lst9 = list({1:"1", 2:"2"})


print(lst9) # OUTPUT – [1, 2]

2 len() lst1 = [1, 2, 3, 4, 5, 6]


counts number of elements. print(len(lst1)) # OUTPUT – 6
3 append() lst1 = [1, 2, 3, 4, 5, 6]
appends single element into list. print(lst1)
lst1.append(7)
print(lst1)
lst1.append("sanjeev")

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

4 extend() lst1 = [1, 2, 3, 4, 5]


append multiple elements into print(lst1)
list. lst1.extend([7, 8])
print(lst1)
lst1.extend("sanjeev")
print(lst1)
lst1.extend([2])
print(lst1)
lst1.extend(2)
print(lst1)

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

1 1. Identify the invalid valid python statement in the following.


D = dict()
E = {}
F= []
G = dict{}
2

Ans. (i) lst.remove(10)


(ii) str1.rplace(‘this’,’That’)
3 Consider the given below Lists L1 & L2 and answer the following using built-in function only:
L1 = [10, 10, 20, 10, 30, 20]
L2 = [0, 1, 2, 1, 2, 0, 1]
1. (a) Write python command to delete last element from list L2.
(b) Write python command to count 20 from list L1.
2. (a) Write python command to add [1, 0, 2] in the end of list L2.
(b) Write python command to sort list L1 in ascending order.
Ans. 1 (a) L2.pop() 1(b) L1.count(20)
Ans. 2 (a) L2.append([1, 0, 2]) (2) b L1.sort()
4 What does the list.pop(a) method do in Python?
(A) Deletes the element at index a from the list
(B) Deletes the first occurrence of value a from the list
(C) Deletes all occurrences of value a from the list
(D) Deletes the last occurrence of value a from the list
5 Given is a Python List declaration:
lst1= [39, 45, 23, 15, 25, 60]
(Answer using built in functions only)
(a) Insert value 90 at index 3 -------- Ans. lst1.insert(3,90)
(b) Display elements of list in reverse -------Ans. lst1.reverse()
(c) Add another list [2,3,4] at end of lst1 ------Ans. lst1.append[2,3,4] ()
(d) Find sum of elements of list ---------Ans. sum(lst1)
6 Identify the invalid statement for list L=[1,2,3,4]
a. L.remove(3) b. L.pop(3) c. L.del(3) d. del L[3]

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

8 (i) Consider the List prices L=[23.811,237.81,238.91] then


(Answer using built in function only)

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

(ii) Consider the List prices L=[“Jan”,”Feb”,”Mar”] then


(Answer using built in function only)

(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

SN Function & Description Example


1 tuple() l2 = tuple ()
Empty tuple. print(l2) # OUTPUT – ()

tuple from string s1 = 'sanju'


l5 = tuple (s1)
print(l5) # OUTPUT – ('s', 'a', 'n', 'j', 'u')

tuple from List t1 = [1, 2, 3, 4, 5]


l6 = tuple (t1)
print(l6) # OUTPUT – (1, 2, 3, 4, 5)

tuple from inputted string l7 = tuple(input("Input tuple Element - ")) print(l7)

OUTPUT – Input tuple Element – 12345


('1', '2', '3', '4', '5')

tuple from Dictionary lst9 = tuple ({1:"1", 2:"2"})


print(lst9) # OUTPUT – (1, 2)
2 len() t1 = (1, 2, 3, 4, 5, 6)
counts number of elements. print(len(t1)) # OUTPUT – 6
3 count() t1 = [5, 5, 3, 4, 5, 6]
counts occurrence of an element. print(t1.count(5)) # OUTPUT – 3
4 index() t1 = (1, 2, 3, 4, 5, 6)
print(t1.index(4))

20
MLL Material, Class XII Computer Science, KVS RO Lucknow 21

gives index of first occurrence of print(t1.index(44))


element.
OUTPUT – 3
ValueError: 44 is not in list
5 sorted() t1 = (5, 5, 3, 4, 5, 6])
create a new list and assign l2 =sorted(t1)
existing tuple in Ascending/ print(l2)
Descending Order. No change in t1 = (5, 5, 3, 4, 5, 6)
existing tuple. l2 = sorted(t1, reverse = True)
print(l2)

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

Questions and Answers:


1

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

3 Find the output of the following code snippet


S=9, (2, 13, 8), 5, (1, 6)
print ( len (S) )
a. 4 b. 7 c. 6 d. Error

Common Mistakes committed by students while writing the answer:


Creating a single element tuple, immutability of tuple, many function of list do not work on tuple.

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

SN Function & Description Example

1 dict() d2 = dict()
Empty dictionary. print(d2)

Using key=value d3 = dict(name="Sanjeev",post="PGT",sub="CSIP")


print(d3)

Non-empty dictionary d4 = dict({'name':"Sanjeev",'post':"PGT",'sub':"CSIP"})


print(d4)

Using Nested List d5 = dict([['name',"Sanjeev"],['post',"PGT"],['sub',"CSIP"]])


print(d5)
Using Nested Tuple d6 = dict((('name',"Sanjeev"),('post',"PGT"),('sub',"CSIP")))
print(d6)
Using List of Tuple d7 = dict([('name',"Sanjeev"),('post',"PGT"),('sub',"CSIP")])
print(d7)
Using Tuple of List d8 = dict((['name',"Sanjeev"],['post',"PGT"],['sub',"CSIP"]))
print(d8)

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

5 items() trs = {'name':"Sanjeev",'post':"PGT",'sub':"CSIP"}


returns all items of print(trs.items())
dictionary as a sequence
of list of tuples OUTPUT –
(key.value) dict_items([('name', 'Sanjeev'), ('post', 'PGT'), ('sub', 'CSIP')])
6 get() trs={'name':"Sanjeev",'post':"PGT",'sub':"CSIP"}
gives item with given key, print(trs.get('name'))
if key not present than print(trs.get('mob',"Not Found"))
print(trs.get('abc'))

22
MLL Material, Class XII Computer Science, KVS RO Lucknow 23

None. None may be


customized. OUTPUT – Sanjeev
Not Found
None
7 update() trs = {'name':"Sanjeev",'post':"PGT",'sub':"CSIP"}
merge a new dictionary print(trs)
into another dictionary. If trs1 = {'mob':9476785270, 'sub':{1:'CS',2:'IP'}}
key is same than existing trs.update(trs1)
key’s value is modified. print(trs)

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 –

{1: 'neha', 2: 'saima', 3: 'avnit', 4: 'ans', 5: 'sk'}


sk
{1: 'neha', 2: 'saima', 3: 'avnit', 4: 'ans', 5: 'sk'}
sk
15 max() trs={'name':"Sanjeev",'post':"PGT",'sub':"CSIP"}
min() print(max(trs))
gives maximum, print(min(trs))
minimum value if print(max(trs.values()))
Dictionary contains same print(min(trs.values()))
type of keys.
OUTPUT – sub
name
Sanjeev
CSIP

Questions and Answers:


1 As a Dictionary is mutable, both Key & Value are also mutable.
False

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

3 Predict the output of the following code snippet


Marks = { ‘Manoj’: 92, ‘Suresh’: 79, ‘Vaibhav’:88 }
print ( list( marks.keys( ) ) )
a. ‘Manoj’ , ’Suresh’, ‘Vaibhav’
b. 92, 79, 88
c. [‘Manoj’, ‘Suresh’, ‘Vaibhav’]
d. (‘Manoj’, ‘Suresh’, ‘Vaibhav’)

5 Write Python Statement.

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

print("Ceiling Value of ",str(num3)," is ",res) Ceiling Value of 2.4 is 3

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

res = math.pow(num1, num2) 5 ^ 3 is 125.0


print(str(num1)," ^ ", str(num2)," is ",res)

res = math.sin(num1) Sin of 5 is -0.9589242746631385


print("Sin of ",str(num1)," is ",res)

res = math.cos(num1) Cos of 5 is 0.28366218546322625


print("Cos of ",str(num1)," is ",res)

res = math.tan(num1) Tan of 5 is -3.380515006246586


print("Tan of ",str(num1)," is ",res)

res = math.degrees(num1) Radian to Degrees of 5 is 286.4788975


print("Radian to Degrees of ",str(num1)," is ",res)
res = math.radians(num1) Degree to Radian of 5 is 0.0872664625
print("Degree to Radian of ",str(num1)," is ",res)
PI 3.141592653589793
pi = math.pi
print("PI ",pi)
e 2.71828182845904
e = math.e
print("e ",e)
Python Standard Library provides statistics module to perform statistic related operations. Don’t forget to
import statistics module
import statistics as st OUTPUT –
lst = [10,20,30,40,50,10,15,25,35,45]
print('List',lst) List [10, 20, 30, 40, 50, 10, 15, 25, 35, 45]
res = st.mean(lst)
print('Mean of List Items',res) Mean of List Items 28
res = st.mode(lst)
print('Mode of List Items',res) Mode of List Items 10
res = st.median(lst)
Median of List Items 27.5
print('Median of List Items',res)

Common mistake by the students:


 Forgets to import module

26
MLL Material, Class XII Computer Science, KVS RO Lucknow 27

Name of Unit: Computational Thinking and Programming – 2 Name of chapter : Functions:


Topic : Functions [Arguments and Parameters, local and global variable]
Gist of topic :
1. Creating user defined function, arguments and parameters,
2. Default parameters, positional parameters,
3. Function returning value(s)
4. Flow of execution, scope of a variable (global scope, local scope)
Questions and Answers:
1. What is the difference between argument and parameters?
Ans :
Parameters Arguments
 Definition: Variables that are declared  Definition: The actual values that are
within a function's definition. passed to a function when it's called.
 Location: Appear within the  Location: Appear within the
parentheses of the function parentheses of the function call.
declaration.
Example:
Function Definition:
#def my_function(param1, param2):
# Function body
#Function Call: my_function(arg1, arg2)
2. What is the difference between global variable and local variable
Ans:
Global Variables Local Variables
 Scope: Csn be used from anywhere  Scope: Can be used only within the
within the program, including inside specific function or block (e.g., loop,
functions. conditional statement) where they are
 Lifetime: Exist throughout the declared.
program's execution.  Lifetime: Exist only during the
 Declaration: Declared outside of any execution of the function or block.
function.  Declaration: Declared inside a function
or block.
global_var = 10 def my_function():
def my_function(): local_var = 5
print(global_var) print(local_var)
3. What is the full form of LEGB rule in python?
Ans: The LEGB Rule in Python stands for: LOCAL ,ENCLOSING, GLOBAL, BUILT-IN
 Local: Variables defined within the current function.
 Enclosing: Variables defined in the enclosing function (if the current function is nested within
another).
 Global: Variables defined at the top-level of the module.
 Built-in: Predefined variables in Python (e.g., len(), print()).
4. What will be the output of the given code?
a=10
def convert(b=20):
a=30
c=a+b
print(a,c)
convert(30)

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)

(End of convert function)

print(a) i.e 10


print(10)
End
5. Write the output of the code given below:
def printMe(q,r=2):
p=r+q**3
print(p)
#main-code
a=10
b=5
printMe(a,b)
printMe(r=4,q=2)
Ans:1005
12
Explanation:
1. Function Definition:
o def printMe(q,r=2): defines a function named printMe that takes two arguments:
 q: Required argument (no default value)
 r: Optional argument with a default value of 2
2. Function Body:
o p=r+q**3: Calculates the value of p as r plus the cube of q.
o print(p): Prints the calculated value of p.
3. Function Calls:
o printMe(a,b):Positional Arguments

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

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


def my_func(var1=100,var2=200):
var1+=10
var2 = var2-10
return var1+var2
print(my_func(50),my_func())
Output:
350 300.
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
8. Assertion (A):-If the arguments in a function call statement match the number and
order of arguments as defined in the function definition, such arguments are called
positional arguments.
Reasoning (R):- During a function call, the argument list first contains default
argument(s) followed by positional argument(s).
Ans: Option : C
Assertion (A) is True.
 Positional Arguments: In Python, when you call a function, you provide values for the arguments.
If you pass these values directly in the order they are defined in the function's definition, they are
called positional arguments.
Reasoning (R) is False.
 Order of Arguments: The order of arguments in a function call typically follows this order:
1. Positional Arguments: These are the arguments that are passed directly to the function in
the order they are defined in the function's definition.
2. Keyword Arguments: These are arguments that are passed using the keyword (parameter
name) followed by the value, allowing you to specify the value for a specific parameter
explicitly.
3. Default Arguments: These are arguments that have default values assigned to them in the
function definition. If no value is provided for a default argument during the function call,
the default value is used.
9. Assertion (A):- key word arguments are related to the function calls.
Reasoning (R):- when you use keyword arguments in a function call, the caller identifies the arguments by
parameter name.

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

 Misunderstanding of Global and Local Variables:


2. Argument Handling:
 Incorrect Number of Arguments: Passing the wrong number of arguments to the function.
 Incorrect Argument Order: Forgetting the order of arguments, especially when using positional
arguments.
 Not Using Default Arguments: Not utilizing default values for parameters when appropriate,
leading to unnecessary code repetition.
 Misunderstanding Keyword Arguments: Not understanding how to use keyword arguments
effectively to improve code readability and flexibility.
3. Return Statements:
 Missing Return Statements: Forgetting to include a return statement when the function is
expected to return a value.
 Returning Incorrect Values: Returning the wrong variable or data type from the function.
 Incorrectly Using return Statements: Using return statements in unexpected places, such as within
loops or conditional blocks.
4. Indentation Errors:
 Incorrect indentation within the function definition or within the function body. Python relies
heavily on indentation to define code blocks.
5. Logic Errors:
 Incorrectly implementing the logic within the function, leading to incorrect results.
 Not considering edge cases or special conditions.
Tips for Students:
 Read the Code Carefully: Analyze the code line by line, paying attention to function definitions,
argument passing, and variable assignments.
 Test with Different Inputs: Test the code with various input values to ensure it works as expected
in different scenarios.
 Break Down the Problem: Divide the problem into smaller, more manageable parts, and then
solve each part individually.
 Practice Regularly: Consistent practice is key to improving coding skills and identifying and
avoiding common mistakes.

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:

• 'r': Read mode (default)


• 'w': Write mode (overwrites content)
• 'a': Append mode (adds content to the end)
• 'r+': Read and write mode

Always close the file after operations using file.close() or a with statement to handle files automatically.

with open('example.txt', 'r') as file:


content = file.read()
# No need to explicitly close the file when using with.

Reading from Files

• file.read(): Reads the entire file as a string.


• file.readline(): Reads a single line from the file.
• file.readlines(): Reads all lines and returns a list of strings.
Eg.
with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())

Writing to Files

• file.write(string): Writes a string to the file.


• file.writelines(list_of_strings): Writes a list of strings to the file.

with open('example.txt', 'w') as file:


file.write("This is a new line.\n")

Appending to Files : Use 'a' mode to append new data without overwriting the file. Eg.

with open('example.txt', 'a') as file:


file.write("Appended content.\n")

Tips

1. Use with for cleaner and safer file handling.


2. For large files, read and process data in chunks or line by line.
3. Be cautious when writing files to avoid overwriting important data

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.

file1 = open('F1.txt', 'r')


Words = 0
for Line in file1:
NewStr = Line
WordsinLine = len(NewStr.split())
Words = Words + WordsinLine
print('The total number of words', Words)
file1.close()

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

 No standard way to represent binary data

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

Name of Unit: Computer Networks Name of Chapter: Computer Network-I


Topic: Computer Hardware (Data communication terminologies………… Introduction to web services)
Gist of the Topic:

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

i. Better immunity against internal and external electromagnetic interferences


ii. Expensive than UTP Cables
3. CO-AXIAL CABLE
It consists of two conductors that share a common axis. The inner conductor is a straight wire and the
outer conductor is a shield that might be braided or a foil.
Characteristics –
1. Carry data for large distance up to 185m – 500m.
2. Less susceptible to electromagnetic fields.
3. Bulkier and less flexible that Twisted par. (Disadvantage)
4. Difficult to install(disadvantage)
5. 2 types – Thicknet(upto 500 mtrs long) and Thinnet (upto 185mtrs)
4. OPTICAL FIBRE - are long, thin strands of glass about thickness of human hair. It is used to transmit data through light
signals over long distances.
Characteristics –
1. Carry data for a very large distance
2. No. of repeaters require are very less as compare to other wired media
3. Not susceptible to electromagnetic fields
4. Installation is complex. (Disadvantage)
5. Parts – Core(glass of plastic though with light travels), Cladding(covering of core, that reflect light back
to core),Protective Coating
B. UNGUIDED MEDIA
1. MICROWAVE
a. Travels in straight lines and cannot penetrate any solid object, therefore for long distance microwave
communication high towers are built and microwave antennas are put on their top
b. Free from land acquisition rights
c. Relatively inexpensive than wired media
d. Offer ease of communication over difficult terrain
e. Sending and receiving antennas need to be properly aligned
2. RADIO WAVE
a. Used for communication over distance ranging from few meters to an entire city.
b. Can penetrate through building easily.
c. Used Cell phones, AM, FM radio.
d. Omni directional
e. Permission from concerted authorities is required for use of radio wave transmission
3. SATELLITE
a. Used for very long distance wireless communication.
b. It covers large area of earth
c. Expensive
d. Require legal permissions.
4. INFRARED
a. Frequency range 300 GHz to 400 THz.
b. Used for short range communication approx. 5m
c. Used in cordless mouse, remote controlled devices
d. They do not pass through solid object
5. LASER
a. Line of sight communication
b. Unidirectional
c. Required laser transmitter and photo sensitive receiver

DATA COMMUNICATION TERMINOLOGIES


1. DATA CHANNEL – medium to carry information or data from one point to another

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.

2. Difference between HTML and XML:

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:

1 Expand the following Terms:


ARPANET, NSFNET, RJ-45
Ans. ARPANET = Advanced research project agency networking
NSFNET=National Science Foundation Network
RJ-45 = Registered Jack
2 Differentiate between Start Topology and Bus Topology. What are the advantages and disadvantages of Star
Topology over Bus Topology?
Ans.
STAR BUS
Each node is connected to each other through Each node is connected to each other though backbone
central node i.e. Switch / Hub cable
If Switch/Hub fails entire network will be stopped If Backbone cable fails entire network will be stopped
Data transmission speed is fast Data transmission speed is slow as compare to Star
More cable is required Less cable is required
Fault Diagnosis is easy Fault Diagnosis is difficult
Adding/Removal of node is easy Difficult as compare to Star to Add/Remove nodes
High cost setup Low cost setup as compare to Star
Signal transmission is not unidirectional Signal transmission is unidirectional
3 Which of the following device send data to every connected node:
(i) Switch (ii) Hub (iii) Router (iv) Gateway
Ans. HUB
4 In which type of switching first the connection is established between sender and receiver and then the data is
transferred?
Ans. Circuit Switching
5 _________ is used to provide short-range wireless connectivity between two electronic devices that within the
distance of 5-10 meters
Ans. Infrared

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.

3. What is the main purpose of a Router ?


Ans. A Router is a network device that works like a bridge to establish connection between two networks
but it can handle networks with different protocols.
4. Define the term IP address with respect to network.
Ans. IP stands for Internet Protocol, gives distinct address (called IP address) to each data packet.
5. Which protocol out of the following is used to send and receive emails over a computer network?
(a) PPP (b) HTTP (c) FTP (d) SMTP
Ans. (d) SMTP
6. Name any two web browsers.
Ans. The most popular browsers are Mozilla Firefox, Microsoft Internet Explorer, Google Chrome, Opera
browser, Apple Safari.
7. Differentiate between URL and domain name with the help of an appropriate example.
Ans.

42
MLL Material, Class XII Computer Science, KVS RO Lucknow 43

Sl. URL Domain Name


No.
1 URL is a full web address used to locate a A domain name is the translated and simpler
webpage. form of a computer's IP address (Logical
address).
2 The whole web address of any website is A domain name is a human-friendly text
represented by a string called a URL. form of the IP address.
3 Example URL is Example of domain name is
'https://cloudflare.com/learning/' 'cloudflare.com'

8. What is the need of protocols ?


Ans. In networking, a protocol is a set of rules for formatting and processing data. Network protocols are
like a common language for computers. The computers within a network may use vastly different software
and hardware; however, the use of protocols enables them to communicate with each other regardless.
9. A Delhi firm is planning to connect to its Marketing department in Kanpur which is approximately 300 km
away. Which type of network out of LAN, WAN or MAN will be formed? Justify your answer.
Ans. Wide Area Network (WAN), because it is a network which spans a large geographical area, often a
country or a continent.
10. Suggest a protocol that shall be needed to provide help for transferring of files between Delhi and Kanpur
branch.
Ans. FTP, File Transfer Protocol, is used for transferring files from one system to another on the Internet.
Common Mistakes committed by students while writing the answer:
1. Full forms not correct or partially correct.
2. Forgets to justify the answers, when asked in question.
3. Do not write correct definitions.

43
MLL Material, Class XII Computer Science, KVS RO Lucknow 44

Name of Unit: Database Management Name of Chapter: Database Concepts


Topic: Database concepts: introduction to database concepts and its need
Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys (candidate key, primary key, alternate
key, foreign key)
Structured Query Language: introduction, Data Definition Language and Data Manipulation Language, data type (char(n),
varchar(n), int, float, date), constraints (not null, unique, primary key), create database, use database, show databases,
drop database, show tables, create table, describe table, alter table (add and
remove an attribute, add and remove primary key), drop table
Gist of the Topic:
DATABASE: A database is an organised collection of interrelated data that serves many applications.
It is generally a computer record keeping system. In a database we can not only store the data but we can also change the
data as per the user requirement.
Database Management System (DBMS): Databases are generally managed by special software called DBMS (Database
Management System) which is responsible for storing, manipulating, maintaining and utilizing the databases.
Various DBMS Software: Oracle, MySQL, Sybase, SQLite, PostgreSQL, DB2, MS Access etc.
Database System: A database along with the DBMS is referred to as database system.
Need for DBMS:
1. Databases reduce redundancy i.e. it removes the duplication of data.
2. Database controls inconsistency i.e. when two copies of the same data do not agree to each other it is called
inconsistency. By controlling redundancy, the inconsistency is also controlled.
3. Databases allows sharing of data.
4. Database ensures data security by the process of authentication and does not allow unauthorized access.
5. Database maintains integrity.
6. Database is maintained in a standard format which helps to interchange the data between two systems.

Relational Database Model:


In Relational Database Model the data is stored in the form of tables i.e. rows and columns.
In Relational Database Model a table is also referred to as a Relation.
In Relation Database Model a column is also referred to as an attribute
In relational database model a row is also referred to as a tuple.
Various other terminologies used in relational data model:
Domain: The pool of all the possible values from which values are derived for a particular column is referred to as a
domain. For example if there 40 students having rollno 1 to 40 and we assigning work to these students then domain for
column rollno is 1 to 40.
Degree: Number of attributes/columns in a relation is referred to as degree of a relation. For example if a table has 5
columns then the degree of a table will be 5.
Cardinality: Number of rows /tuples in a relation is referred to as the cardinality of a relation.
For example if a table has 6 rows then the cardinality of a table will be 6.
Note: Heading row is not included while calculating cardinality of a table

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

EmpNo Ename Gender DeptNo Salary Comm


1 Ankita F 10 20000 1200
2 Sujeet M 20 24000 NULL

44
MLL Material, Class XII Computer Science, KVS RO Lucknow 45

3 Vijaya F 10 28000 2000


4 Nitin M 30 18000 3000
5 Vikram M 30 24000 1700

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.

Table: Department (Parent Table)


DeptNo Dname Location
10 HR New Delhi
20 Accounts Mumbai
30 Sales Chennai
40 IT Kolkata

Table: Employee (Child Table)


EmpNo Ename Gender DeptNo Salary Comm
1 Ankita F 10 20000 1200
2 Sujeet M 20 24000 NULL
3 Vijaya F 10 28000 2000
4 Nitin M 30 18000 3000
5 Vikram M 30 24000 1700

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.

Types of SQL Commands:


1. DDL or Data Definition Language:
DDL or Data Definition Language actually consists of the SQL commands that can be used to define the database schema.
It simply deals with descriptions of the database schema and is used to create and modify the structure of database
objects in the database. DDL is a set of SQL commands used to create, modify, and delete database structures but not
data.
DDL commands :- Create, Alter, Drop, Describe
2. DML or Data Manipulation Language:
Commands that allow you to perform data manipulation e.g., retrieval, insertion, deletion and modification of data stored
in a database object.
DML commands:- Select, Insert, Delete, Update.

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’

INTEGRITY CONSTRAINTS: A constraint is a condition or check applicable on a field or set of fields.


NULL If a column in a row has no value/ unknown value, then column is said to be NULL.
It is default constraint if no constraint given during table creation.
NOT NULL Ensures that a column cannot have NULL value.
UNIQUE Ensures that all values in a column are different
PRIMARY KEY Used to uniquely identify a row in the table

DATABASE COMMANDS OR DDL COMMANDS:


CREATING DATABASE IN MYSQL To create a database in the system
CREATE DATABASE <databasename>; In order to create a database School, we write command as:
CREATE DATABASE School;
VIEW EXISTING DATABASE To view the names of all existing databases in the system.
SHOW DATABASES; SHOW DATABASES;
ACCESSING A DATABASE To open/access already existing database.
USE<databasename>; to access a database named School, we write command as:
USE School;
REMOVING DATABASE To remove a database from the system
DROP DATABASE <databasename>; to remove/delete a database named School, we write command
as:
DROP DATABASE School;
VIEWING TABLES IN DATABASE To view the names of tables present in currently accessed
database
SHOW TABLES; SHOW TABLES;
CREATING TABLES IN MYSQL To create a new table in the current database
CREATE TABLE<Tablename> In order to create table EMPLOYEE given below, we write:
( CREATE TABLE EMPLOYEE
columnname1 datatype(size) constraint, (
columnname2 datatype(size) constraint, EMPID INT PRIMARY KEY,
. ENAME CHAR(30) NOT NULL,
. POST VARCHAR(15)
); );
When a table is to be created, its columns are named, data types
and sizes are supplied for each column. Constraint are optional.
VIEWING STRUCTURE OF A TABLE To display the structure of table on screen
we can use DESCRIBE or DESC command, as to view the structure of table EMPLOYEE, command is :
per following syntax: DESCRIBE EMPLOYEE ; OR
DESCRIBE | DESC <tablename> ; DESC EMPLOYEE;
REMOVING TABLE To remove a table from the database. Once the DROP command
is issued, the table will no longer be available in the database.

46
MLL Material, Class XII Computer Science, KVS RO Lucknow 47

DROP TABLE<TABLENAME>; To remove/delete a table named Employee, we write command


as:
DROP TABLE Employee;
MODIFYING STRUCTURE OF TABLE ALTER TABLE command is used to change the structure of the
existing table. It can be used to add new column/constraints or
drop existing columns/constraints or modify the datatype/size of
existing columns of table
For adding new column in table: To add a new column mobileno in table Employee:
ALTER TABLE<TABLE NAME> alter table employee
ADD COLUMNNAME DATATYPE(SIZE); add mobileno int;
For removing column in table: To remove a column mobileno in table Employee:
ALTER TABLE<TABLE NAME> alter table employee
DROP COLUMNNAME; drop mobileno;
For adding primary key constraint in table: To add primary key constraint to existing column ecode in table
ALTER TABLE<TABLE NAME> Employee:
ADD PRIMARY KEY(COLUMNNAME); alter table employee
add primary key(ecode);
For removing primary key constraint in table: To remove primary key constraint in table Employee:
ALTER TABLE<TABLE NAME> alter table employee
DROP PRIMARY KEY; drop primary key;
For modify the existing columns in table To modify size of existing column ename from 30 to 60 in table
ALTER TABLE<TABLE NAME> Employee:
MODIFY COLUMNNAME DATATYPE(SIZE); ALTER TABLE Employee
MODIFY ename varchar(60);
Questions and Answers:
1. Name any two RDBMS software.
2. You create a table named EMPLOYEES. What among the following is possible?
A. It can be referred to as eMPLOYEES B. It can be referred to as EMPLoyees
C. It can be referred to as employees D. All of the above
3. __________ is the number of columns in a table and ________ is the number of rows in the table.
a) Cardinality, Degree b) Degree, Cardinality c) Domain, Range d) Attribute, Tuple
4.Layna creates a table STOCK to maintain computer stock in vidyalaya. After creation of the table, she has entered data
of 8 items in the table.

Based on the data given above answer the following questions:


i Identify the most appropriate column, which can be considered as Primary key.
ii What is the degree and cardinality of the given table?
iii. If 3 columns are added and 5 rows are deleted from the table stock, what will be the new degree and cardinality of
the above table?
5. Which aggregate function can be used to find the cardinality of table?

47
MLL Material, Class XII Computer Science, KVS RO Lucknow 48

(A)sum() (B)count(*) (C)avg() (D)max()


6.If a table has 5 Candidate keys then it will have___ Primary keys and ___Alternate keys
a) 1,5 b) 1,1 c) 1,4 d) 4,1
7. _________is an attribute or set of attributes eligible to become primary key.
(a) PrimaryKey (b) ForeignKey (c) CandidateKey (d) Alternate Key
8. Candidate keys which are not selected as Primary key is known as ……………….
A. Primary Key B. Candidate Key C. Alternate Key D. Foreign Key
9. Select the correct statement, with reference to RDBMS:
a) NULL can be a value in a Primary Key column
b) ' ' (Empty string) can be a value in a Primary Key column
c) A table with a Primary Key column cannot have an alternate key.
d) A table with a Primary Key column must have an alternate key.
10. _____ is a non-key attribute, whose values are derived from the primary key of some other table.
(A) Foreign Key (B) Candidate Key (C) Primary Key (D) Alternate Key
11. Which of the following statements is FALSE about keys in a relational database?
(A) Any candidate key is eligible to become a primary key.
(B) A primary key uniquely identifies the tuples in a relation.
(C) A candidate key that is not a primary key is a foreign key.
(D) A foreign key is an attribute whose value is derived from the primary key of another relation.
12. Assertion: The FOREIGN KEY constraint is used to establish links between tables.
Reason: A FOREIGN KEY in one table points to a FOREIGN KEY in another table.
a) Both A and R are True and R is 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
13. Mr. Ravi is creating a field that contains alphanumeric values and fixed lengths. Which MySQL data type should he
choose for the same?
(A) VARCHAR (B) CHAR (C) LONG (D) NUMBER
14. Which of the following statements about the CHAR and VARCHAR datatypes in SQL is false?
(A) CHAR is a fixed-length datatype, and it pads extra spaces to match the specified length.
(B) VARCHAR is a variable-length datatype and does not pad extra spaces.
(C) The maximum length of a VARCHAR column is always less than that of a CHAR column.
(D) CHAR is generally used for storing data of a known, fixed length.
15. Sushma created a table named Person with name as char(20) and address as varchar(40). She inserted a name as
“Adithya Varman” and address as “Anna Nagar IVth Street”. State how much bytes would have been saved for this record.
a)(20,22) b)(20,40) c)(14,40) d)(14,22)
16. The default date format in MySQL is:
(a) DD/MM/YYYY (b) YYYY/MM/DD c) MM-DD-YYYY (d) YYYY-MM-DD
17. Literals of which SQL data type are enclosed in quotes?
a) Char & Varchar b) Float c) Date d) (a) & (c)
18. Which two constraints can make a primary key of a table.
a. NOT NULL, Default b. NULL, Unique c. NOT NULL, Unique d. None of these
19. Which is not a constraint in MySQL?
a) Unique b) Distinct c) Primary key d) Not Null
20. What constraint should be applied on a column of a table so that it becomes compulsory to insert the value for that
column?
21. What constraint should be applied to a table column to ensure that it can have multiple NULL values but cannot have
any duplicate non-NULL values?
22. What constraint should be applied on a column of a table to ensure that it can have unique and NOT NULL values?
23. Identify DDL command from following mysql command.

48
MLL Material, Class XII Computer Science, KVS RO Lucknow 49

a) alter b) select c) insert d)update


24. The structure of the table/relation can be displayed using
(A) view command. (B) describe (C) show (D) select
25. The command is used to access/open database in MySQL is-
(a) Open <databasename>; (b) USE <databasename>; (c) Access <databasename>; (d) (a)&(c) both
26. To see all the existing databases which command is used?
(a)Show database; (b) Show databases; (c) Show database(); (d) Show all databases;
27. Which of the following will display all the existing tables in current database:
a) SELECT * FROM <databasename>; b) DISPLAY TABLES; c) SHOW TABLES; d) USE TABLES;
28. Which is a valid CREATE TABLE statement?
(a) Create table emp add(id integer(3)); (b) Create table emp(id integers(3));
(c) Create table emp modified(id integer(3)); (d) Create table emp(id integer(3));
29. Which SQL command can modify the structure of an existing table, such as adding/removing columns?
(A) ALTER TABLE (B) UPDATE TABLE (C) MODIFY TABLE (D) CHANGE TABLE
30. Which of the following commands will delete the table from MYSQL database?
a) delete table b) drop table c) remove table d) alter table
31. Which command will be used by Aman to remove the table Fees from the database School.
a) DELETE FROM Fees; b) DROP TABLE Fees; c) DROP DATABASE Fees; d) DELETE FEES FROM SCHOOL;
32. Assertion (A) : DROP is a DDL command
Reason(R ) : It is used to remove all the content of a database object
a) Both A and R are True and R is 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
33. ______command is used to remove primary key from the table in SQL.
(a) update (b)remove (c) alter (d)drop
34. Which SQL command can change the degree of an existing relation?
a) update (b)alter (c) delete (d)drop
35. Write a query to create table STORE with following attributes and constraints:
ItemNo – numeric, primary key, ItemName – character of size 20, Price – numeric.
36. Write an SQL command to add a column brand in a table product with string data type and it should not contain NULL
value.
37. Write an SQL command to remove the column remarks from the table name customer.
38. Write an SQL command to assign F_id as primary key in the table named Flight
39. Write an SQL command to remove the Primary Key constraint from a table STUDENT. Adm_No column is the primary
key of the table.
40. Give any two features of MySQL.
ANSWER KEY
1 Oracle, MySQL 2 D 3 B 4 I stockid ii 5,8 iii 8,3
5 B 6 C 7 C 8 C 9 B 10 A 11 C 12 C
13 B 14 C 15 A 16 D 17 D 18 C 19 B
20 NOT NULL 21 UNIQUE 22 PRIMARY KEY 23 A 24 B
25 B 26 B 27 C 28 D 29 A 30 B 31 B 32 C
33 C 34 B 35 CREATE TABLE STORE 36 ALTER TABLE
(ITEMNO INT PRIMARY KEY, PRODUCT
ITEMNAME VARCHAR(20), ADD BRAND
PRICE INT); VARCHAR(20) NOT
NULL;
37 ALTER TABLE 38 ALTER TABLE FLIGHT 39 ALTER TABLE STUDENT
CUSTOMER ADD PRIMARY KEY (F_ID); DROP PRIMARY KEY;

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

Name of Unit: Database Management System Name of Chapter: DML Commands


Topic: DML Commands upto group by
Gist of the topic:
DML commands are used to manipulate data in a database, whereas DDL commands are used to
define or modify the structure of a database.
DML Commands are SELECT, INSERT, DELETE, UPDATE.
Insert Command:
The INSERT command is used to add new data to a database table. The basic syntax is:
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Example: INSERT INTO customers (name, email, phone) VALUES ('John Doe',
'[email protected]', '123-456-7890');
Delete Command:
The DELETE command is used to delete data from a database table. The basic syntax is:
DELETE FROM table_name WHERE condition;
Example: DELETE FROM customers WHERE name = 'John Doe';
Select Command:
The SELECT command is used to retrieve data from a database table. The basic syntax is:
SELECT column1, column2, ... FROM table_name WHERE condition;
Example: SELECT name, email, phone FROM customers WHERE country = 'USA';
Update Command:
The UPDATE command is used to modify data in a database table. The basic syntax is:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
Example: UPDATE customers SET email=”[email protected]” where name=”john”;

Other point of the chapter


Operators:
Mathematical Operators: + (addition), - (subtraction), * (multiplication), / (division), %
(modulus)
For example-- Select name, basic + DA from employee;
The above query displays name column and sum of basic and da.
Relational Operators: = (equal to), <> (not equal to), > (greater than), < (less than), >= (greater
than or equal to), <= (less than or equal to)
Example- SELECT name, email, phone FROM customers WHERE age > 18;
Logical Operators: AND (logical and), OR (logical or), NOT (logical not)
Example: SELECT name, email, phone FROM customers WHERE age > 18 AND country =
'USA';
Aliasing: Aliasing is used to give a temporary name to a table or column.
Syntax: SELECT column1 AS alias_name FROM table_name;
Example: SELECT name AS customer_name FROM customers;
In the result of this query the customer_name is displayed in place of name;
Distinct Clause: The DISTINCT clause is used to retrieve unique values from a database table.
Syntax: SELECT DISTINCT column1, column2, ... FROM table_name;
Example: SELECT DISTINCT country FROM customers;
Where Clause: The WHERE clause is used to filter data based on conditions.

50
MLL Material, Class XII Computer Science, KVS RO Lucknow 51

Syntax: SELECT column1, column2, ... FROM table_name WHERE condition;


Example: SELECT name, email, phone FROM customers WHERE country = 'USA';
In and Between Operators:
- In Operator: Used to retrieve data that matches a list of values.
Syntax: WHERE column_name IN (value1, value2, ...);
Example: SELECT name, email, phone FROM customers WHERE country IN ('USA', 'Canada',
'Mexico');
- Between Operator: Used to retrieve data that falls within a range of values.
Syntax: WHERE column_name BETWEEN value1 AND value2;
Example: SELECT name, email, phone FROM customers WHERE age BETWEEN 18 AND 65;
Order By Clause: The ORDER BY clause is used to sort data in ascending or descending order.
Syntax: SELECT column1, column2, ... FROM table_name ORDER BY column_name
ASC/DESC;
Example: SELECT name, email, phone FROM customers ORDER BY name ASC;

Null and Not Null:


- Null: Represents an unknown or missing value.
syntax: WHERE column_name IS NULL;
Example: SELECT name, email, phone FROM customers WHERE address IS NULL;
- Not Null: Represents a value that is not null.
Example: SELECT name, email, phone FROM customers WHERE address IS NOT NULL;
Like Operator: The LIKE operator is used to retrieve data that matches a pattern. The basic syntax
is:
WHERE column_name LIKE pattern;
Example: SELECT name, email, phone FROM customers WHERE name LIKE '%John%';

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

O_Id C_Name Product Quantity Price


1001 Jitendra Laptop 1 12000
1002 Mustafa Smartphone 2 10000
1003 Dhwani Headphone 1 1500
Note: The table contains many more records than shown here.
A) Write the following queries:
(I) To display the total Quantity for each Product, excluding Products with total Quantity less than
5.
(II) To display the orders table sorted by total price in descending order.
(III) To display the distinct customer names from the Orders table.
(IV) Display the sum of Price of all the orders for which the quantity is null.
B) Write the output
(I) Select c_name, sum(quantity) as total_quantity from orders group by c_name;
(II) Select * from orders where product like '%phone%';
(III) Select o_id, c_name, product, quantity, price from orders where price between 1500 and
12000;
(IV) Select max(price) from orders;
Answer:
A) (I) select Product, sum(Quantity) from orders group by product having sum(Quantity)>=5;

(II) select * from orders order by Price desc;


(III) select distinct C_Name from orders;
(IV) select sum(price) as total_price from orders where Quantity IS NULL;
B) (I) C_Name | Total_Quantity
--------- |---------------
Jitendra | 1
Mustafa | 2
Dhwani | 1

(II) O_Id | C_Name | Product | Quantity | Price


----- |-------- |------------ |---------- |-------
1002 | Mustafa | Smartphone | 2 | 10000
1003 | Dhwani | Headphone | 1 | 1500

(III) O_Id | C_Name | Product | Quantity | Price


----- |---------- |------------ |---------- |-------
1001 | Jitendra | Laptop | 1 | 12000
1002 | Mustafa | Smartphone | 2 | 10000
1003 | Dhwani | Headphone | 1 | 1500

(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

PCode PName UPrice Rating BID


P01 Shampoo 120 6 M03
P02 Toothpaste 54 8 M02
P03 Soap 25 7 M03
P04 Toothpaste 65 4 M04
P05 Soap 38 5 M05
P06 Shampoo 245 6 M05

Table: BRAND
BID BName
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove

Write SQL queries for the following:


(i) Display product name and brand name from the tables PRODUCT and BRAND.
(ii) Display the structure of the table PRODUCT.
(iii) Display the average rating of Medimix and Dove brands
(iv) Display the name, price, and rating of products in descending order of rating.

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

You might also like