Class - XI Subject: Computer Science
Class - XI Subject: Computer Science
UNIT- 1 CBSE
Boolean Algebra
cbseacademic.nic.in/web_material/doc/cs/2_Computer_Science_Python_ClassXII.pdf
Unit – 4 Introduction to Boolean Algebra
Chapter -1 and 3
Variable
Variable, in Python, is an object that is used to store values viz. numeric (e.g., 345), string (e.g.,
‘Python’) or any combination of alphanumeric characters (e.g., CD67). In Python, we can use an
assignment statement to assign specific value to a variable.
Example :
Type:
It tells the data type of the object.
Value:
The value assigned to the object. To bind a value to a variable, we use the assignment operator
(=).
A variable name:
• Allowed characters : a-z, A-Z, 0-9 and underscore (_)
• should begin with an alphabet or underscore.
• should not be a keyword.
Write a Python Program to illustrate the use of variables in calculating simple interest and
print Identity, Type and Value of each variable used.
L-value and R-value concept
In any assignment statement, the assignable object (e.g. variable) must appear on the left side
of the assignment operator else python will report an error. In this case, the assignable object is
called L-value.
The value to be assigned (or any expression producing value) must appear on the right side of the
assignment operator. In this case, the value (or expression resulting in value) is called R-value.
CBSE – Sorting
cbseacademic.nic.in/web_material/doc/cs/2_Computer_Science_Python_ClassXII.pdf
Argument (Reference: CBSE Text Book, Computer Science, Class XI, Unit-3, Chapter - 2 : Functions)
Arguments are the value(s) provided in function call/invoke statement.
Default Parameter
When, in a function definition, one or more parameters are provided with a default value. The
default value assigned to the parameter should be constant only. Only those parameters which are at the
end of the list can be given a default value.
We cannot have a parameter on left with a default value, without assigning default values to parameters
lying on its right side.
Positional Argument
The arguments which get assigned to parameter according to their position. An argument list must have
any positional arguments followed by any keyword’s arguments.
Note: Refer Keyword argument (CBSE TextBook, Computer Science, Class XI, Unit-3, Chapter - 2: Functions)
for better understanding.
Example:
10, 9 and 8 are positional arguments in the following calls:
area_Triangle(10,9,8)
Recursion in Python
What is Recursion?
Recursion actually refers to the process of a function calling itself. The function which calls
itself is called a recursive function.
Recursion works by breaking a larger problem into smaller ones. It is useful when we need to
perform the same operation on a variable a number of times.
Let us take an example to explain Recursion.
Problem : To find the factorial of a given number . say 4, we shall use recursion.
4!= 4 x 3 x 2 x 1=24
Code using a recursive function:
def fact(n)
if n = = 1:
return 1
else This is the recursive function call. Here the function
return n * fact(n-1) fact calls itself with n-1 as the argument, which again
calls itself till the function returns 1.
print (fact(4))
The first call transfers control to the function fact() with value 4. Then the function is called
again with the value 3 and so on till we reach a base case or a call that returns 1 in this case.
So here, the function fact() is called 4 times and each time the call is nested within the
previous call. The evaluation of last call is returned to the second last and so on.
Recursion makes the code look neat and is simpler to write in terms of logic. But it
requires more memory due to the nested function calls.
Looping vs Recursion
We can also use a function with a loop to find the factorial of a number. The code is a bit
more complex and the control remains within the function as the loop iterates.
Here control is transferred to the function when it is called with the value 4.
Within the function the orange dotted lines indicate iteration. Once the loop
breaks the return statement is executed thus control comes out to the call and the
factorial is printed.
Advantages of recursion
1. The code requires less lines.
2. Breaking large complex programs becomes easier.
3. Makes code look more modular.
Disadvantages
1. The program may never terminate if not used properly or too much nesting is there.
2. More difficult to understand than loops.
def fibonacci_sum(n):
if n == 1 or n == 2:
return 1
else:
return (fibonacci_sum(n - 1) + (fibonacci_sum(n - 2)))
print(fibonacci_sum(6))
The function fibonacci () is invoked with n as 6 here. The return statement nests two
recursive function calls . Let us see how this works through visualizing the calls
fibonacci(6)
= fibonacci(5) + fibonacci(4)
= fibonacci(4) + fibonacci(3) + fibonacci(3) +fibonacci(2)
= fibonacci(3) + fibonacci(2) + fibonacci(2) +fibonacci(1)+fibonacci(2)+fibonacci(1)+1
=fibonacci(2)+fibonacci(1)+1+1+1+1+1+1
=1+1+6
=8
def sum(Num):
if len(Num) == 1:
return Num[0]
else:
return Num[0] + sum(Num[1:])
In the above program, sum() is a recursive function with the recursive call within
the else part of the if construct.
3. Calculate a number raised to a power using recursion.
def power(x,y):
if y==0:
return 1
elif y==1:
return x
elif x==0:
return 0
else:
return x*power(x,y-1)
print(power(4,2))
In this program the function power is called recursively when the value of x is more than 0.
In computer science, the efficiency of a program is measured in terms of the resources it consumes. Two
of the most critical resources, which a program consumes are time and memory. For better efficiency, a
program execution should consume less resources. In the modern times, we consider the idea of efficiency
in terms of time only. So, in simple terms, we can say that an efficient program should take less time to
execute.
Efficient Program
Execution
Time
Inefficient Program
In 1843, Ada Lovelace (The first computer programmer) emphasised the importance of efficiency
concerning time when applying Charles Babbage's mechanical analytical engine.
We have to calculate its execution time to measure the efficiency of code. Execution time of code may
vary from computer to computer depending upon the configuration of the system (i.e., Processor speed,
RAM, Cache, OS, Compiler/Interpreter version etc.). We can calculate the number of fundamental
operations in a code's execution. Assuming that each major operation takes one unit of time to execute,
if a code performs 't' number of fundamental operations, then its execution time becomes 't' units.
In the world of computing, we express these complexities with capital O, also called Big O notation. Note
that over here "O" means order, i.e. "order of complexity".
So, we can say that Big O notation is used to measure the complexity of any algorithm or a code. Let us
consider the following N number of statements expected to be executed in code:
Statement 1
Statement 2
...
Statement N
Then the total time can be calculated by adding the time consumed by each of the statement:
Example 1:
N=int(input('N'))
for i in range(N):
print(i)
for i in range(N):
for j in range(N):
print(j)
So, the complexity of the above code in terms of Big O notation will be O(N2)
Example 2:
N=int(input("N:"))
for i in range(1, N+1):
p=p*i
print(p)
Complexity = 1 + N*1 + 1
= N
So, the complexity of the above code in terms of Big O notation will be O(N)
[Considering only the dominant term]
Example 3:
N=int(input("N:"))
if(N<0):
return
for i in range(1, N+1):
p1=p1*i
M=int(input("M:"))
for i in range(1, M+1):
p2=p2*i;
print(p1 + p2)
So, the complexity of the above code in terms of Big O notation will be O(N+M)
[Considering only the dominant terms]
Example 4:
N=int(input("N:"))
sum=0;
for j in range(1, N+1):
for i in range(1, N+1):
p=p*i
sum+=p
print(sum)
Complexity = 1 + 1 + N* (N*1) + 1
= 1 + 1+ N2 + 1
So, the complexity of the above code in terms of Big O notation will be O(N2)
In simple ways, we can also find the execution time required by a code
(Using time module to check start and end time of programs for executing the code)
import time
Start = time.time()
def PrimeCheck(N):
if N > 1: # Prime numbers are always greater than 1.
for i in range(2, N//2+1):
if (N % i) == 0:
print(N," is not Prime Number")
break
else:
print (N," Prime Number")
else:
print(num," is neither prime nor composite")
Num = int(input("Enter a Natural Number: "))
PrimeCheck(Num)
End = time.time()
print("Total Execution Time:",End-Start)
Output :
Enter a number : 627
627 is not Prime Number
Total Execution Time: 2.990596055984497
(Note: The time can vary on different systems)
import math
import time
Start = time.time()
def PrimeCheck(N):
if N > 1:
for i in range(2,int(math.sqrt(N))+1):
if (N % i) == 0:
print(N," is not a prime number")
break
else:
print(N," is a prime number")
else:
print(N," is neither Prime nor Composite")
Num = int(input("Enter a Natural Number: "))
PrimeCheck(Num)
End = time.time()
print("Total Execution Time:",End-Start)
Output:
Enter a Natural Number: 627
627 is not a prime number
Total Execution Time: 1.9446911811828613
(Note: The time can vary on different systems)
import time
Start = time.time()
def Sum_N(N):
S=0
for i in range(1, N+1):
S+=i
print(S)
Num = int(input("Enter a Natural Number: "))
Sum_N(Num)
End = time.time()
print("Total Execution Time:",End-Start)
Output:
Enter a Natural Number: 100000
50005000
Total Execution Time: 78.48986077308655
(Note: The time can vary on different systems)
import time
Start = time.time()
def Sum_N(N):
print(N*(N+1)/2)
Num = int(input("Enter a Natural Number: "))
Sum_N(Num)
End = time.time()
print("Total Execution Time:",End-Start)
Output :
Enter a Natural Number: 100000
5000050000.0
Total Execution Time: 4.043231248855591
(Note: The time can vary on different systems)
Binary File Handling
1. Adding a Record at the end of the file.
import pickle
'''
Function 1: A function AddRecord() to add new records at the end of the binary
file "student" using list. The list should consist of Student No, Student Name
and Marks of the student.
'''
def AddRecords():
Student=[]
while True:
Stno =int(input("Student No:"))
Sname=input("Name")
Marks=int(input("Marks"))
S=[Stno,Sname,Marks]
Student.append(S)
More=input("More(Y/N)?")
if More=='N':
break
F=open("students","ab")
pickle.dump(Student,F)
F.close()
while True:
CH=input("A:Add U:Update D:Display Q:Quit ")
if CH=='A':
AddRecords()
elif CH=='U':
Update()
elif CH=='D':
Display()
else:
Break
Sample Output:
A:Add U:Update D:Display Q:Quit A
Student No:12
NameArun Jha
Marks98
More(Y/N)?Y
Student No:15
NameTaran Taran
Marks76
More(Y/N)?Y
Student No:19
NameRiya Sen
Marks87
More(Y/N)?N
A:Add U:Update D:Display Q:Quit D
12 Arun Jha 98
15 Taran Taran 76
19 Riya Sen 87
A:Add U:Update D:Display Q:Quit U
Student No:15
Record found...
Existing Name: Taran Taran
New NameTaran Singh
New Marks92
Record updated
A:Add U:Update D:Display Q:Quit Q
CSV File handling
CSV (Comma Separated Values) file format is the most common format for tabulated data to be used in
any spreadsheet tool (Calc, Google Sheets, Excel) and any database. A CSV file stores tabular data
(numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more
fields, separated by commas. The name CSV comes from the use of commas as a field separator for this
file format.
The following are some of the examples of CSV files without header:
CSV File content with 3 Fields/Columns
1,Simran,80
2,Rishabh,99
CSV File content with 4 Fields/Columns with comma as separator:
12,"Simran",3400,"34,ABC Colony, DL"
14,"Rishabh",4300,"R-90,XYZ Nagar, DL"
In Python, we use (import) the csv module to perform read and write operations on csv files. The csv
module in Python’s standard library presents classes and methods to perform read/write operations on
CSV files.
We will make use of the writer () in a csv module which will return a writer object of the csv module to
write the content of a sequence onto the file and the reader object to read the content from a csv file
into a sequence.
As we have already seen in case of text and binary file handling, open() function is required to connect to
the external file and close() function to disassociate with the external file. We will make use of the same
functions for csv files too. Here also with the open function, we will use “w” (write) as the second
parameter to write the content in a new file, "r" (read) as the second parameter to read the content from
an existing file and “a” (append) as the second parameter to add new content below the existing content.
# Open a CSV File for writing content at the bottom of an existing file
# It will create a new file, if file does not exist
Csvfile=open('student.csv','a', newline='')
writer()
This function in the csv module returns a writer object that converts data into a delimited string and
stores it in a file object. The function needs a file object with write permission as a parameter. Every
row written in the file issues a newline character. To prevent additional space between lines, the
newline parameter is set to ‘’.
CSV.writer class provides two methods for writing to the CSV file. They are writerow() and writerows()
function.
writerow()
This function writes items in an iterable (list, tuple or string), separating them by comma character.
Syntax:
writerow(fields)
writerows()
This function takes a list of iterables as a parameter and writes each item as a comma separated line
of items in the file.
Syntax:
writerows(rows)
import csv
#------------------------------------------------------------------------#
# To create a CSV File by writing individual lines
#------------------------------------------------------------------------#
def CreateCSV1():
Csvfile=open('student.csv','w', newline='') # Open CSV File
Csvobj =csv.writer(Csvfile) # CSV Object for writing
while True:
Rno =int(input("Rollno:"))
Name =input("Name:")
Marks=float(input("Marks:"))
Line=[Rno,Name,Marks]
Csvobj.writerow(Line) # Writing a line in CSV file
Ch=input("More(Y/N)?")
if Ch=='N':
break
Csvfile.close() # Closing a CSV File
The writer function returns a writer object that converts the data into a
delimited string and stores it in a file object. Every row written in the file
issues a new line character. To avoid additional lines between rows, the newline
is set to ’’.
#------------------------------------------------------------------------#
# To create a CSV File by writing all lines in one go
#------------------------------------------------------------------------#
def CreateCSV2():
Csvfile=open('student.csv','w', newline='')# Open CSV File
Csvobj =csv.writer(Csvfile) # CSV Object for writing
Lines=[]
while True:
Rno=int(input("Rollno:"))
Name=input("Name:")
Marks=float(input("Marks:"))
Lines.append([Rno,Name,Marks])
Ch=input("More(Y/N)?")
if Ch=='N':
break
Csvobj.writerows(Lines) # Writing all lines in CSV file
Csvfile.close() # Closing a CSV File
#------------------------------------------------------------------------#
# To read and show the content of a CSV File
#------------------------------------------------------------------------#
def ShowAll():
Csvfile=open('student.csv','r', newline='')# Opening CSV File for reading
Csvobj=csv.reader(Csvfile) # Reading the CSV content in object
for Line in Csvobj: # Extracting line by line content
print(Line)
Csvfile.close() # Closing a CSV File
#------------------------------------------------------------------------#
while True:
Option=input("1:CreateCSV 2:CreateCSVAll 3:ShowCSV 4:Quit ")
if Option=="1":
CreateCSV1()
elif Option=="2":
CreateCSV2()
elif Option=="3":
ShowAll()
else:
break
In case the newline is not present in the open function, the newline character is taken as ‘\r\n’. This
is indicated by the presence of blank lines in the CSV file or the output which is displayed.
Here is the program where open function is used without the newline argument:
#------------------------------------------------------------------------#
# To create a CSV File by writing individual lines
#------------------------------------------------------------------------#
def CreateCSV1():
Csvfile=open('student.csv','w') # Open CSV File
Csvobj =csv.writer(Csvfile) # CSV Object for writing
while True:
Rno =int(input("Rollno:"))
Name =input("Name:")
Marks=float(input("Marks:"))
Line=[Rno,Name,Marks]
Csvobj.writerow(Line) # Writing a line in CSV file
Ch=input("More(Y/N)?")
if Ch=='N':
break
Csvfile.close() # Closing a CSV File
#------------------------------------------------------------------------#
# To create a CSV File by writing all lines in one go
#------------------------------------------------------------------------#
def CreateCSV2():
Csvfile=open('student.csv','w') # Open CSV File
Csvobj =csv.writer(Csvfile) # CSV Object for writing
Lines=[]
while True:
Rno=int(input("Rollno:"))
Name=input("Name:")
Marks=float(input("Marks:"))
Lines.append([Rno,Name,Marks])
Ch=input("More(Y/N)?")
if Ch=='N':
break
Csvobj.writerows(Lines) # Writing all lines in CSV file
Csvfile.close() # Closing a CSV File
#------------------------------------------------------------------------#
# To read and show the content of a CSV File
#------------------------------------------------------------------------#
def ShowAll():
Csvfile=open('student.csv','r')# Opening CSV File for reading
Csvobj=csv.reader(Csvfile) # Reading the CSV content in object
for Line in Csvobj: # Extracting line by line content
print(Line)
Csvfile.close() # Closing a CSV File
#------------------------------------------------------------------------#
while True:
Option=input("1:CreateCSV 2:CreateCSVAll 3:ShowCSV 4:Quit ")
if Option=="1":
CreateCSV1()
elif Option=="2":
CreateCSV2()
elif Option=="3":
ShowAll()
else:
break
Important: To create a python Library make sure you are using no other versions of python and
pip is only installed on a default path.
Module: A Module is a file containing python definitions, functions, variables, classes and
statements with .py extension.
[Creation module is covered in Class XI Chapter - 7 Functions in NCERT]
1 Create a new folder with a name you want to give to a package along
with a sub folder in it.
2 Create modules and save within the sub folder. [Note that the modules
are the executed files]
4 Store the package content within the file __init__.py via importing all
the modules created.
Note: The Python interpreter recognizes a folder as a package, if it
contains __init__.py file
Example:
To create a package Calci containing two modules Simple.py and Arith.py
We have created the Library named “Calci”. To create the Library follow the steps and see the
structure of the folders and files.
(Where Calci is a folder containing three files: Simple.py, Arith.py and __init__.py. The file
__init__.py contains the contents of the files Simple.py and Arith.py, which can be done by simply
importing these files.)
Step 1: We have created the folder calci and under that the folder "nav" which is the actual name
of the library.
Step -2 Create the file .py name “Simple1.py” in the folder nav.
To check whether your Library is properly installed or not. Write the following commands:
import nav
dir(nav) #It will display the name of all the user-defined and system modules
along with functions
help(“nav”) #It will display the content of the package.
Importing library
Data is organized into rows, columns and stored in tables. The rows (tuples) are indexed to make it easier to find
relevant information.
Front End in database refers to the user interface or application that enables accessing tabular, structured or raw data
stored within it. The front end holds the entire application programming utility for data, requests input and sends it to
the database back-end. Form or any user interface designed in any programming language is Front End. (Python is
used as front end). Data given by the database as a response is known as the Back-End database. (We will be using
Python as Front-End and MySQL as Back-End)
1. Start Python
2. Import Packages required for establishing connectivity
3. Create Database
4. Open and establish a connection to the database
5. Create a cursor object or instance
6. Execute a query
7. Extract data from the result set
8. Clean up the environment
Establish a connection
For database interface/database programming, a connection must be established. Before establishing
connection there must be MySQL installed on the system (Link: https://downloads.mysql.com/archives/community/)
and a database and table are already created.
Installation of mysql.connector
We can use any connector to just one word needs to change in program rest of the code always same.
In the following way, we can establish a connection with the MySQL database through mysql.connector.
In all the ways, we are specifying host, user, password and database name as arguments.
the database is an optional argument if we want to create a database through programming later on.
Cursor object :
The MySQLCursor class instantiates objects that can execute operations such as MySQL statements. Cursor objects
interact with the MySQL server using a MySQLConnection object.
The above code will create a database school and display all the databases stored on your computer.
On successful execution of the above program, a table named student with three attributes roll no, name, age will
be created in the database school.
The following code will demonstrate how to insert data into a table during run time
The following code will demonstrate adding a new attribute to the table at run time
Above program will add a new attribute marks in the table student and will display the structure of the table
The following code will display data from a table during runtime.
MySQLCursor.fetchall() Method
This method fetches all rows of a query result set and returns a list of tuples. If no more rows are available,
it returns an empty list.
MySQLCursor.fetchone() method
This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are
available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects.
MySQLCursor.fetchmany() method
rows = cursor.fetchmany(size=1)
This method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available,
it returns an empty list.
In the above program delete query will delete a record with rollno=1. commit()method is necessary to call for a
database transaction.
The following code will edit the marks scored by roll no 2 to 99.
(Students are advised to develop a menu-driven program using the above concepts for better understating of
python MySQL database interface. This concept can be used in Project work to be completed by the students.)
To Manage Database Transaction:
Python MySQL Connector provides the following method to manage database transactions.
Table Data
The following code explains the use of a select query for searching a specific record from a table.
The above code will take a name from the user and that name is searched in the table student using the SELECT
query, the result will be shown with the help of my cursor collection.
Practice Exercise:
Consider scenario of a school where each student is supposed to enroll for two lab Courses. The structure of the
Student and Lab table is as shown below.
Note: Lab1_Code & Lab2_Code (Student Table) are Foreign Key referencing Lab_code (Lab table).
STUDENT
Roll_No Name Class Session Gender Address Lab1_Code Lab2_Code
1 Ajay 12 2020-21 M Delhi PHY CHE
2 Ramesh 12 2020-21 M Delhi PYT BIO
3 Sumedha 12 2020-21 F Delhi CHE PYT
4 Suresh 12 2020-21 M Ghaziabad BIO PHY
5 Vijay 12 2020-21 M Noida PYT MAT
LAB
Lab_Code Lab_Name Instructor_First_Name
BIO BIOLOGY SANTOSH
CHE CHEMISTRY RAJAT
MAT MATHS SUDHIR
PHY PHYSICS LALIT
PYT PYTHON SUNIL