MLL CS Xii
MLL CS Xii
“SESSION 2025-26
KENDRIYA VIDYALAYA SANGATHAN
Zonal Institute of Education & Training, Gwalior
OUR MENTOR:
MR. B.L. MORODIA
Deputy Commissioner & Director
KVS Zonal Institute of Education and Training, Gwalior
Course Coordinator
MRS. ANITA KANAJIA, T.A. ECONOMICS
RESOURCE PERSONS
1. MRS SANGEETA M CHAUHAN ,
PGT CS , PM SHRI K V NO3 GWALIOR
2. MR. ALOK GUPTA
PGT COMP, PM SHRI K V ETAWAH
VETTED BY:
1. MR RAJU DIXIT ,
PGT CS, PM SHRI K V ALIGARH
2. MR. RAKESH KUMAR SINGH YADAV
PGT CS, PM SHRI K V DOGRA LINES MEERUT CANTT
3. MR. SUNIL KUMAR BHELE
PGT CS, PM SHRI K V PUNJAB LINES MEERUT CANTT
4. MR. MANISH GUPTA
PGT CS, PM SHRI K V HATHRAS
5. MR PANKAJ SINGH
PGT(CS) , PM SHRI KV TALBEHAT
Identifiers/Data types/Conversions/Evaluation of Expression
Features in Python
1. Free and Open Source. ...
2. Object-Oriented Language. ...
3. GUI Programming Support. ...
4. Cross-platform….
5. Portable language and case sensitive ...
6. Interpreted Language….
Tokens :
The Smallest individual unit of the program is called Token.
Data Types: to identify the type of data and associated operation of handling it.
Sequence Data Type : list,tuple,string
Mapping: Dictionary
Operators:
Arithmetic operators +,-,*, //(floor), /, %(modulus), a=10,b=3 a=10,b=3
**(exponent) c=10//3 d=a%b
print(c ) print(d)
output 3 output 1
+,-
or Boolean or
Types of comment:
i. Single line comment (#) – comments only on a single line.
e.g., a=7 # 7 is assigned to variable ‘a’
ii. multi-line comment (‘‘‘...........’’’) – Comments multiple line.
iii inline comment (#) if a==b: # compare value of a and b
Type conversion : Type conversion is the process of changing the data type of a value in
Python.
1. implicit (done by system(automatically))
2. explicit (type casting or user defined conversion)
Implicit type conversion happens automatically when Python encounters mixed data types in an
expression. It converts the data type to a higher-order data type to prevent data loss. For
example, when adding an integer to a float, Python implicitly converts the integer to a float
before performing the addition.
Example
a=10+20.7
print(a) #30.7
Explicit type conversion(type casting) is when the programmer manually converts the data type
of a value using built-in functions like int(), float(), str(), list(), tuple(), set(), and dict().
Example:
print(int(234.78)) #234
Conditional Statements/Errors
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if…elif…else Statement :
if-elif-else statement in Python is used for multi-way decision-making. This allows us to check
multiple conditions sequentially and execute a specific block of code when a condition is True. If
none of the conditions are true, the else block is executed.
If-elif-else-Statement:-
Example:
i = 25
# Checking if i is equal to 10
if (i == 10):
print("i is 10")
# Checking if i is equal to 15
elif (i == 15):
print("i is 15")
# Checking if i is equal to 20
elif (i == 20):
print("i is 20")
# If none of the above conditions are true
else:
print("i is not present")
Iterative Statement
Iterative Statement/Repetition of a set of statements in a program is made possible using looping
constructs.
The ‘for’ Loop
The for statement is used to iterate over a range of values or a sequence. The for loop is executed
for each of the items in the range. These values can be either numeric, or they can be elements of
a data type like a string, list, tuple or even dictionary.
Syntax of the for Loop :
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
The ‘while’ Loop
The while statement executes a block of code repeatedly as long as the control condition of the
loop is true. The control condition of the while loop is executed before any statement inside the
loop is executed. After each iteration, the control condition is tested again and the loop continues
as long as the condition remains true. When this condition becomes false, the statements in the
body of loop are not executed and the control
is transferred to the statement immediately following the body of the while loop. If the condition
of the while loop is initially false, the body is not executed even once.
Syntax of while loop:-
while test_condition:
body of while
Break and Continue Statement
In certain situations, when some particular condition occurs, we may want to exit from a loop
(come out of the loop forever) or skip some statements of the loop before continuing further in the
loop. These requirements can be achieved by using break and continue statements, respectively.
Lists in Python :
Definition:
- A list is an ordered, mutable (changeable) collection of items.
- Defined using square brackets [].
Example:
my_list = [1, 2, 3, "apple", True]
Key Features:
- Ordered: Items have a defined index.
- Mutable: You can change, add, or remove elements.
Common Operations:
my_list.append("banana") # Add item
my_list[0] = 100 # Change item at index 0
del my_list[1] # Delete item at index 1
len(my_list) # Get length
Tuples in Python :
Definition:
- A tuple is an ordered, immutable (unchangeable) collection of items.
- Defined using parentheses ().
Example:
my_tuple = (1, 2, 3, "apple", True)
Key Features:
- Ordered: Items have a fixed position.
- Immutable: Cannot be changed after creation.
Common Operations:
len(my_tuple) # Get length
my_tuple[1] # Access item at index 1
Single-item Tuple:
one_item = (5,) # Note the comma!
List vs Tuple :
Brackets [] ()
Mutable Yes No
Use Case When data may change When data should stay constant
Dictionaries :
● In python a dictionary is a python data type which can store mappings in form of key-value
pairs.
● A dictionary is an ordered sequence(in recent python versions) of key-value pairs.
● A Key and value in a key-value pair in a dictionary are separated by a colon. Multiple key-
value pairs in a dictionary are separated by comma(s) and are enclosed within curly braces.
● Keys of the dictionaries are immutable types such as Integers or Strings etc. but since
values of dictionaries are mutable hence dictionaries are considered as mutable data type.
Dictionary Description
Methods/Functions
keys() Returns a view object that displays a list of all the keys in the dictionary.
values() Returns a view object containing all dictionary values.
items() Return the list with all dictionary keys along with their values
get() Returns the value for the given key
clear() Deletes all items from the dictionary
copy() Returns a shallow copy of the dictionary
fromkeys() Creates a dictionary from the given sequence
pop() Returns and removes the element with the given key
popitem() Returns and removes the item that was last inserted into the dictionary.
setdefault() Returns the value of a key if the key is in the dictionary, otherwise it inserts the key
with a value to the dictionary
update() Updates the dictionary with the elements from another dictionary or an iterable of
key-value pairs. By using this method we can include new data or merge it with
existing dictionaries.
AMonths={1:"Jan",2:"Feb",3:"Mar",4:"Apr",5:"May",6:"Jun",
7:"July",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"}
P y t h o n
-6 -5 -4 -3 -2 -1 Backward index
STRING SLICING
Slicing is a way to extract portion of a string by specifying the start and end indexes. The syntax
for slicing is string[start:end], where start starting index and end is stopping index (excluded).
STRING OPERATORS:
Two basic operators + and * are allowed
+ is used to combine two String (Concatenation)
*is used for replication(repetition)
Functions in String:
Function Description
Answer:
1. green revolution 2. GREEN REVOLUTION
3. 0 4. 12 5. 18 6. ['Green India', 'New India'] 7. ['Green', 'India,New', 'India']
8. Green India,Old India 9. False 10. Green India,New India
A Python module is a file that contains a collection of related functions, classes, and variables that
can be used in other Python programs. Modules are a way to organize and reuse code, making it
easier to write and maintain large programs.
Importing Modules
1. import module_name: Imports the entire module, and you can access its functions and variables
using the module name.
2. from module_name import function/variable: Imports a specific function or variable from the
module, and you can use it directly.
3. from module_name import *: Imports all functions and variables from the module, and you can
use them directly.
The Python random module provides functionalities for generating random numbers. Here are
some basic functions:
Random Number Generation
1. random(): Returns a random floating-point number between 0 and 1.
2. randint(a, b): Returns a random integer between a and b (inclusive).
Random Sequence Operations
1. choice(seq): Returns a random element from the sequence seq.
2. shuffle(seq): Randomly rearranges the elements of the sequence seq.
Functions :
In Python, a function is a block of code that can be executed multiple times from different parts
of your program. Functions are useful for:
Benefits of Functions
1. Code Reusability: Functions allow you to reuse code, reducing duplication and improving
maintainability.
2. Modularity: Functions help to break down a large program into smaller, manageable modules.
3. Readability: Functions make your code more readable by providing a clear and concise way to
perform a specific task.
Defining a Function
In Python, you define a function using the def keyword followed by the function name and
parameters in parentheses. Here's a basic example:
def greet(name):
print(f"Hello, {name}!")
Function Components
1. Function Name: The name of the function.
2. Parameters: Variables that are passed to the function when it's called.
3. Function Body: The code that gets executed when the function is called.
4. Return Value: The value that the function returns to the caller.
Scope of Variable
A variable is a name used to store data.
Local variable:
● Created inside a function. * Can be used only inside that function.
Example:
def show():
x=5 # local variable
print(x)
Global variable:
● Created outside of all functions. * Can be used inside and outside any function.
Example:
x = 10 # global variable
def show():
print(x)
Returning of Values
● A function can send back a result using the return statement.
● return ends the function and gives back a value.
● You can return one or more values.
Types of Parameters
Parameters are values given to a function when it is called.
a. Required Parameters
● Must be given in the correct order.
Example:
def greet(name):
print("Hello", name)
greet("Amit")
b. Default Parameters
● Have a value already set. * If no value is given, the default is used.
Example:
def greet(name="Guest"):
print("Hello", name)
greet() # Output: Hello Guest
c. Keyword Parameters
● You give the name of the parameter while calling.
Example:
def greet(name, message):
print(message, name)
greet(message="Hi", name="Ravi")
d. Variable-length Parameters
● When the number of arguments is not fixed.
● *args – for many values
● **kwargs – for many key=value pairs
Example:
def show(*names):
for name in names:
print(name)
show("Ram", "Shyam")
MLL-TEXT FILE
Opening a text file - It is done using the open() function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, the full address of the
file should be written in place of the filename.
Text File open modes –
Closing a text file – This is done by using close( ) function.
File_object.close( )
Opening a file using with clause – the syntax is -
with open(file_path, mode) as file:
Here - file_path is the path to the file to open, and
Mode is the mode of operation on the file. Eg. read, write etc.
The seek(offset[, from]) method changes the current file position. The offset argument indicates
the number
of bytes to be moved. The from argument specifies the reference position from where the bytes
are to be moved.If from is set to 0, it means use the beginning of the file as the reference position
and 1 means use the current position as the reference position and if it is set to 2 then the end of
the file would be taken as the reference position.
Binary Files
Binary files store data after converting it into binary language (Os and 1s), there is no EOL (End
Of Line) character. This file type returns bytes. This is the file to be used when dealing with non-
text files such as images or exe.
To write data into a binary file, we need to import Pickle module. Pickling means converting
structure (data types) into byte stream before writing the data into file. Pickle module has two main
functions:
1. pickle.dump(): To write the Object into the file
Syntax: pickle.dump(object_to_write,file_object)
2. pickle.load(): To read the Object from the file
Syntax: container_obj=pickle.load(file_object)
Program to write record in a binary file:
import pickle
f=open("myfile. dat ","wb")
for i in range(5):
r=input("Enter roll:")
n=input("Enter name:")
m=input("Enter marks:")
d={"roll":r,"name":n,"marks":m}
pickle.dump(d,f)
print("successfully done!!")
f.close()
Program to append record in a binary file:
import pickle
f=open("myfile.dat","ab")
for i in range(5):I
r=input("Enter roll:")
n=input("Enter name:")
m=input("Enter marks:")
d={"roll":r,"name":n,"marks":m}
pickle.dump(d,f)
print("successfully done!!")
f.close()
Program to read all records from a binary file:
import pickle
f=open("myfile.dat","rb")
while True:
try:
record=pickle.load(f)
print(record)
except EOFError:
break
f.close()
CSV
CSV file: A CSV (Comma Separated Values) file is a plain text file that stores tabular data in a
simple format. Each line in the file represents a row, and columns are separated by commas.
Advantages of using CSV files:
Simple and Easy to Use
• CSV files are plain text files, which makes them easy to create, read, and edit using simple
text editors like Notepad or tools like Excel.
Lightweight and Compact
• Since they are text-based, CSV files are smaller in size compared to formats like Excel
(.xlsx), making them ideal for transferring and storing data.
Widely Supported
• Almost all programming languages (like Python, Java, C++) and applications (Excel,
Google Sheets, databases) support reading and writing CSV files.
Simple and Easy to Use
• CSV files are plain text files, which makes them easy to create, read, and edit using simple
text editors like Notepad or tools like Excel.
Lightweight and Compact
• Since they are text-based, CSV files are smaller in size compared to formats like Excel
(.xlsx), making them ideal for transferring and storing data.
Widely Supported
• Almost all programming languages (like Python, Java, C++) and applications (Excel,
Google Sheets, databases) support reading and writing CSV files.
➢ A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-
In/Last-Out (FILO) manner.
➢ In stack, a new element is added at one end and an element is removed from that end
only. The insert and delete operations are often called push and pop.
➢ Python's built-in data structure list can be used as a stack. List's append() function is used
to add elements to the top of the stack while pop() removes the element in LIFO order.
➢ Also, underflow happens when we try to pop an item from an empty stack. Overflow
happens when we try to push more items on a stack than it can hold.
Program to Demonstrate Push() and Pop() operations on Stack:
def ADDCustomer(Cust):
n = int(input("Enter Customer no: ")) # Main program
nm = input("Enter Customer name: ") Cust = []
s = int(input("Enter salary: ")) while True:
a = (n, nm, s) print("\n1. PUSH")
Cust.append(a) print("2. POP")
print("Customer added:", a) print("3. EXIT")
print("Current Stack:", Cust) ch = input("Choose any
option: ")
def DeleteCustomer(Cust): if ch == '1':
if not Cust: ADDCustomer(Cust)
print("Stack Empty") elif ch == '2':
else: DeleteCustomer(Cust)
v = Cust.pop() elif ch == '3':
print("Element being deleted:", v) break
print("Current Stack:", Cust) else:
print("Choose
correctoption")
Interface Python with mySQL
Interfacing Python with MySQL involves connecting a Python application to a MySQL database
to perform operations such as data retrieval, insertion, updating, and deletion. This note will guide
you through the process of setting up the interface, executing SQL queries, and handling results.
We will use the mysql-connector-python library, which is a popular choice for interfacing
Python with MySQL.
To install the mysql-connector-python library, run the following command:
pip install mysql-connector-python
Connecting to MySQL Database
The first step in interfacing Python with MySQL is to establish a connection to the database.
Establishing a Connection
To establish a connection, you need to import the mysql.connector module and use
the connect method. Here’s an example:
import mysql.connector
# Establishing the connection
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase")
# Checking if the connection was successful
if conn.is_connected():
print("Connected to MySQL database")
Closing the Connection
It is essential to close the connection after completing the database operations to free up
resources.
# Closing the connection conn.close()
Executing SQL Queries
Creating a Cursor Object
A cursor object allows you to execute SQL queries and fetch results.
cursor = conn.cursor()
Executing a Query
You can use the execute method to run SQL queries.
# Executing a query
cursor.execute("SELECT * FROM tablename")
Fetching Results
After executing a SELECT query, you can fetch the results using methods
like fetchall, fetchone, or fetchmany.
# Fetching all rows
rows = cursor.fetchall()
COMPUTER NETWORK
Q.NO. PARTICULARS
1. What is Database?
2. What is the full forms of SQL?
3. Write names of two command of DDL & DML
4. Find out DDL & DML Commands from the following:
INSERT, DELETE, ALTER, DROP
5. Write a query to display all records from the table.
6. What is a primary key?
7. Write one difference between DDL and DML.
8. A_____________ is a collection of records.
9. In a database table, each column is called a __________.
16. Which command is used to show structure of the table named employee?
17. Write the SQL command to display all records from a table named student
18. Aman wants to remove the table Product from the database SHOP which command
will he use from the following.
19. Write MySQL statements for the following:
i. To create a databse named FOOD
ii. To create a table named Nutrients based on the following specification:
Column Data Type Constraints
Name
Food_Item Varchar(20) Primary Key
Calorie Integer
20. . Consider the following table stored in a database SHOP:
Table: Product
Pcode Pname Qty Price
100 Tooth Paste 100 78.0
101 Soap 500 20
102 Talc Powder 50 45.0
Q.No. Answer
1. A database is a collection of related data.
2. Structured Query Language
3. DDL Commands- CREATE, ALTER, DROP
DML Commands: , INSERT, DELETE, UPDATE, SELECT
4. DDL: ALTER, DROP
DML: INSERT, DELETE
5. SELECT * FROM table_name;
6. A column or group of columns that uniquely identifies each row.
7. DDL- Defines and modifies the structure of database objects like tables, schemas,
indexes etc. i.e. create, alter, drop
DML- it is used to manage data within existing tables. It Changes the content of the
database. i.e. select, update, insert, delete
8. Table
9. Field / Column/ attribute/ data item
10. Where
11. Distinct
12. Select
13. Order by
14. Primary key is used to identify each record uniquely in the table. or
A primary key is a column (or a set of columns) in a database table that uniquely
identifies each row in that table.
15. LIKE
16. Describe employee;
17. SELECT * FROM student;
18. b) Drop table Product
19. i. create database FOOD
ii. create table Nutrients (Food_Item varchar(20) primary key,
20. (i) degree-4 Cardinality-3
(ii) alter table product add (supcode char(20));