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

Booklet XII CS 2024-25

Uploaded by

LAWANIYA SHARMA
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)
114 views124 pages

Booklet XII CS 2024-25

Uploaded by

LAWANIYA SHARMA
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/ 124

ST.

GEORGE’S SCHOOL
ALAKNANDA, NEW DELHI

CLASS : XII
COMPUTER SCIENCE (083)

2024-2025
Assignment Booklet
Computer Science CLASS-XII
Code No. 083

2024-25
1. Prerequisites
Computer Science- Class XI
2. Learning Outcomes Student should be able to
a) apply the concept of function.
b) explain and use the concept of file handling.
c) use basic data structure: Stacks
d) explain the basics of computer networks.
e) use Database concepts, SQL along with connectivity between Python and SQL

Unit No Unit Name Marks

1 Computational Thinking and Programming – 2 40

2 Computer Networks 10

3 Database Management 20

Month Syllabus

March 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, insert, delete, select, operators (mathematical,
relational and logical), aliasing, distinct clause, where clause, in, between,
order by, meaning of null, is null, is not null, like, update command, delete
command, aggregate functions (max, min, avg, sum, count), group by,
having clause, joins: cartesian product on two tables, equi-join and natural
join

Interface of python with an SQL database: connecting SQL with Python,


performing insert, update, delete queries using cursor, display data by
using connect(), cursor(), execute(), commit(), fetchone(), fetchall(),
rowcount, creating database connectivity applications, use of %s format
specifier or format() to perform queries

April Revision of Python topics covered in Class XI.

Functions: types of function (built-in functions, functions defined in module, user


defined functions), creating user defined function, arguments and parameters,
default parameters, positional parameters, function returning value(s), flow of
execution, scope of a variable (global scope, local scope)

May Exception Handling: Introduction, handling exceptions using try-except-finally


blocks ● Introduction to files, types of files (Text file, Binary file, CSV file),
relative and absolute paths

July Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a
text file, opening a file using with clause, writing/appending data to a text file
using write() and writelines(), reading from a text file using read(), readline() and
readlines(), seek and tell methods, manipulation of data in a text file

Binary file: basic operations on a binary file: open using file open modes (rb, rb+,
wb, wb+, ab, ab+), close a binary file, import pickle module, dump() and load()
method, read, write/create, search, append and update operations in a binary file

August CSV file: import csv module, open / close csv file, write into a csv file using
writer(),writerow(),writerows() and read from a csv file using reader()

Data Structure: Stack, operations on stack (push & pop), implementation of stack
using list.

September Half Yearly Examination

October Evolution of networking: introduction to computer networks, evolution of


networking (ARPANET, NSFNET, INTERNET)

Data communication terminologies: concept of communication, components of


data communication (sender,receiver, message, communication media, protocols),
measuring capacity of communication media (bandwidth, data transfer rate), IP
address, switching techniques (Circuit switching, Packet switching)

Transmission media: Wired communication media (Twisted pair cable, Co-axial


cable, Fiber-optic cable), Wireless media (Radio waves, Micro waves, Infrared
waves)

Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router,
Gateway, WIFI card)
Network topologies and Network types: types of networks (PAN, LAN, MAN,
WAN), networking topologies (Bus, Star, Tree)

Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET,
VoIP

Introduction to web services: WWW, Hyper Text Markup Language (HTML),


Extensible Markup Language (XML), domain names, URL, website, web
browser, web servers, web hosting

November PreBoard Examination

December PreBoard Examination

S. No Unit Marks (30)

1 Lab Test:
1. Python program (60% logic + 20% 8
documentation + 20% code quality)
2. SQL queries (4 queries based on one or two 4
tables)

2 Report file: 7
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using one
table / two tables.
● Minimum 4 programs based on Python - SQL
connectivity

3 Project (using concepts learnt in Classes 11 and 12) 8

4 Viva 3
St. George’s School, Alaknanda
Assignment : Database Management
1. Display the name of all the databases of your system.
2. Create a database with name SGS
3. Open the database and make it as current database.
4. Create DEPT table with DEPTID as Primary Key.

DEPTID DNAME LOCATION

10 SALES KOKATA

20 FINANCE MUMBAI

30 HR DELHI

5. Insert 3 records in dept table.


6. Create EMP table with EMPNO as Primary Key and DEPTID as foreign key.

EMPNO ENAME JOB HIREDATE SAL COMM DEPTNO

1 BLAKE CLERK 2000-12-12 8000 20

2 JOHN SALESMAN 2020-06-10 7000 1000 10

3 ALLEN MANAGER 2019-05-16 20000 20

4 SHABNAM CLERK 1998-10-13 15000 10

5 DANIEL SALESMAN 2022-10-10 4000 5000 10

7. Insert 5 records in EMP table


8. Display all the records (all columns) from table Emp.
9. Display EmpNo and EName of all employees from table Emp.
10. Display distinct Sal of employees from table Emp.
11. Show the Structure of table Emp
12. Write a query to display EName and Sal of Employees whose salary is greater than or equal to 8000 from
table Emp.
13. Write a Query to display employee name, salary and department number who are not getting commission
from table Emp.
14. Write a Query to display employee Number, name, sal and sal*12 as Annual Salary whose commission is not
NULL from table Emp.
15. Write a Query to display employee name and salary of those employees who don’t have their salary in the
range of 8500 to 20000.
16. Write a Query to display name, job, salary, and HireDate of employees who are hired between February 20,
2000, and May 1,2010. Order the query in ascending order of HireDate.
17. Write a Query to display the name and hire date of all employees who were hired in 1998.
18. Write a Query to display the name, job title and salary of the employee who do not have manager.
19. Write a Query to display the name of the employee whose name contains ‘A’ as third alphabet.
20. Write a Query to display the name of the employee whose name contains ‘T’ as the last alphabet.
21. Write a Query to display the name of an employee whose name contains ‘M’ as first alphabet ‘L’ as third
alphabet.
22. Write a Query to display the name of the employee who is having ‘L’ as any alphabet of the name.
23. Write a Query to display employee name and HireDate of employees who are employed after Employee
‘BLAKE’.
24. Write a Query to Display the Sum, Average, Highest and Lowest salary of the employees.
25. Write a Query to Display the Sum, Average, Highest and Lowest salary of the employees grouped by
department number.
26. Write a Query to Display the Sum, Average, Highest and Lowest salary of the employees grouped by
department number and sub-grouped by job.
27. Write a query to display the number of employee with same job.
28. Write a query to display the average of Highest and lowest salary of each department.
29. Write a query to display the employee name and job for all employee in the same department as ‘ALLEN’·
30. Write a query to display the EName, Salary and DName for all employees using tables Emp and Dept.
SQL -1
TABLE : EMPLOYEE

Column name Datatype Size Constraint

Ecode Integer 5 Primary Key

Name Varchar 20 Can never to left empty

Dept Varchar 20 Default “HR”

Date_of_birth Date 10

Gender Char 1

Designation Varchar 20

Salary Integer 10

Ecode Name Dept Date_of_birth Gender Designation Salary


101 Sunita Sales 06-06-1995 F Manager 25000
102 Neeru Office 05-07-1993 F Clerk 12000
103 Raju Purchase 05-06-1994 M Manager 26000
104 Neha Sales 08-08-1995 F Accountant 18000
105 Nishant Office 08-10-1995 M Clerk 10000
106 Vinod Purchase 12-12-1994 M Clerk 10000

i. Display the list of all the databases of your system.


ii. Create a database with name XI.
iii. Open the database XI.
iv. Display the name of all tables in database XI.
v. Write command to create EMPLOYEE table.
vi. Display the structure of EMPLOYEE table.
vii. Insert the above data in EMPLOYEE table.
viii. Display the detail of all employees of EMPLOYEE table.
ix. Display Name, Salary and gender of all employees from EMPLOYEE table.
x. Display the detail of all employees who are working as ‘Clerk’ or ‘Manager’.
xi. Add a column Contact_No varchar(30) in employee table.
xii. Increase the salary of all female employees by 10%.
xiii. Remove the detail of all employees whose salary is in between 12000 and 20000.
xiv. Display name, designation of employees whose name starts with “N” letter.
xv. Display the detail of all employees in ascending order of their salary.

SQL - 2
Consider the following table Product. Write SQL queries for the following statements

TABLE : PRODUCT

P_ID ProductName Manufacturer Price Quantity

TP01 Talcom Powder Ponds 40 50

TP02 Talcom Powder Johnson 80 60

FW06 FaceWash Lux 45 20

BS01 Bath Soap Patanjali 55 40

SH06 Shampoo Ponds 120 10

FW12 Face Wash Patanjali 90 20

1. Create the above table with P_ID as primary key.


2. Insert all data.
3. Display all records.
4. Add a new column Amount.
5. Update Amount field by Price * Quantity.
6. Display all data in ascending order of amount.
7. Display Product name, Amount, discount offered where discount is 10% of
Amount.
8. Increase the price of Lux manufacturer by 10%.
9. Display total number of manufacturers.
10. Display maximum and minimum quantities.
11. Display names of products whose manufacturer name starting with P.
12. Display names of products whose manufacturer is either Lux or Ponds.
13. Display the structure of the table.
14. Display total amount.
15. Delete the record whose P_id is ending with 6.

SQL - 3

Consider the table stock given below


Write SQL commands to:
a. Display the average amount of each Loan Type
b. Display details in the increasing order of the Interest
c. Display the total amount from each loan type with interest greater than 9
d. Display maximum and minimum Amount of all account holder whose name starts
with A.
e. Display sum of amount of Acc_Nos HD1003, HD1006 and HD1008.
f. Display names of account holders whose amount >=50000 and <=100000.
SQL - 4

Table : TRAINER

TID TNAME CITY HIREDATE SALARY

101 Sunaina Mumbai 1998-10-15 90000

102 Anamika Delhi 1994-12-24 80000

103 Deepti Chandigarh 2001-12-21 82000

104 Meenakshi Delhi 2002-12-25 78000

105 Richa Mumbai 1996-01-12 95000

106 Maniprabha Chennai 2001-12-12 69000

Table : COURSE

CID CNAME FEES STARTDATE TID

C201 AGDCA 12000 2018-07-02 101


C202 ADCA 15000 2018-07-15 103

C203 DCA 10000 2018-10-01 102

C204 DDTP 9000 2018-09-15 104

C205 DHN 20000 2018-08-01 101

C206 O LEVEL 18000 2018-07-25 105

Write SQL queries for the following:

1. Create the tables Trainer (TID is primary key) and Course (CID is primary key)

2. Insert the given data into the respective tables.


3. Display the structure of the tables.
4. Display the Trainer Name, City & Salary in descending order of their Hiredate.
5. To display the TNAME and CITY of Trainer who joined the Institute in the month of
December 2001.
6. To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and
COURSE of all those courses whose FEES is less than or equal to 10000.
7. To display number of Trainers from each city.
8. To increase the fees of the course by 10% where the fee >=5000 and <=12000.
9. Display the Trainer Name, City, hiredate and Salary of the trainers whose name starts with
M.
SQL - 5

Consider the following tables SUBJECT and TEACHER.

Table – Subjects Table - Teachers

Code Title Mark_Th Mark_pr TCode Name Code

301 English 80 20 1 Prakash 301


Jain

041 Mathematics 80 20 2 S Sarangi 041

083 Comp Science 70 30 3 TG 043


Mathew

042 Physics 70 30 4 Sutapa 301


Moitra

043 Chemistry 70 30 5 Vinod 042


Sharma

048 Painting 60 40 6 Victor M 083

7 Arjun 043
Sharma

Write SQL commands for the flowing statements:

1. Create the tables Subjects (Primary key Code) and Teachers (Primary key TCode).
2. Insert the given data.
3. To display the names of all the subjects for which practical marks are 0.
4. To display the total number of teachers in each subject separately.
5. To display the names of all the teachers in the ascending order of the Sub_Code.
6. To display each subject’s details along with Total_Marks in each subject from the table
SUBJECTs where (Total_Marks = Marks_Theory + Marks_Practical).
7. Write SQL statement to display each teacher’s name along with his/her respective subject
name from the tables TEACHER and SUBJECT.
SQL : 6

Create TEACHER table with the following structure:

Column name Datatype Size Constraint

Tno Integer 5 Primary Key

Tname Varchar 20 Can never to left empty

Subject Varchar 20 Default “Science”

Salary Integer 10

Create STUDENT table with following structure

Column name Datatype Size Constraint

Rollno Integer 5 Primary Key

Sname Varchar 20 Can never to left empty

Gender Char 1 Default “F”

Marks Integer 3

Tno Integer 5 Reference key from Teacher table

i. Create Teacher and Student tables.


ii. Display Teacher name and student name from teacher and student tables.

iii. Remove the detail of all students whose marks are below 33.
iv. Display subject and number of teachers teaching same subject.
v. Insert a record in teacher table.
vi. Display the detail of all students in ascending order of their marks

SQL : 7
Table: STORE

SNo SName Area

S01 ABC Computronics GK II

S02 ALL Infotech Media CP

S03 Tech Shoppe Nehru Place

S04 Geeks Tecno Soft Nehru Place

S05 Hitech Tech Store CP

Table: ITEM

INo IName Price SNo

T01 Mother Board 12000 S01

T02 Hard Disk 5000 S01

T03 Keyboard 500 S02


T04 Mouse 300 S01

T05 Mother Board 400 S03

T06 Key Board 400 S03

T07 LCD 6000 S04

T08 LCD 5500 S05

T09 Mouse 350 S05

T10 Hard Disk 4500 S03

a. Create STORE and ITEM tables, where SNO is foreign key.

b. Insert data in the above defined tables.

c. To display IName and Price of all the Items in ascending order of their price.

d. To display SNo and SName of all Stores located in CP.

e. To display Minimum and Maximum Price of each IName from the table Item.

f. Decrease the price of all items by 5% whose name starts with ‘K’ and ends with ‘d’.

g. To display IName, Price of all items and their respective SName where they are available.

SQL : 8
Table: SUPPLIER

SUPCODE SNAME CITY

S01 GET ALL INC KOLKATA

S02 EASY MARKET CORP DELHI

S03 DIGI BUSY GROUP CHENNAI

Table: product

PID PNAME QTY PRICE COMPANY SUPCODE

101 DIGITAL CAMERA 120 12000 RENIX S01


14X

102 DIGITAL PAD 11i 100 2200 DIGI POP S02

103 PEN DRIVE 16 GB 500 1100 STOREKING S01

104 LED SCREEN 32 70 28000 DISPEXPERTS S02

105 CAR GPS SYSTEM 60 12000 MOVEON S03

1. Create Products and suppliers tables, where SUPCODE is foreign key..

2. To display the details of all the products in the ascending order of the product names (i.e.,
PNAME).

3. To display the product name and the price of all those products, whose price is in the range
of 10,000 and 15,000 (both values inclusive).

4. To display the names of those suppliers, who are either from DELHI or from CHENNAI.
5. To display the names of the companies and the products in the descending order of the
company names.

SQL : 9

TABLE : SENDER

SenderID SenderName SenderAddress SenderCity

ND01 R Jain 2, ABC Appts New Delhi

MU02 H Sinha 12, Newtown Mumbai

MU15 S Jha 27/A, Park Street Mumbai

ND50 T Prasad 122-K, SDA New Delhi

TABLE : RECIPIENT

RecID SenderID RecName RecAddress RecCity

KO05 ND01 R 5, Central Avenue Kolkata


Bajpayee

ND08 MU02 S Mahajan 116, A Vihar New


Delhi
MU19 ND01 H Singh 2A, Andheri East Mumbai

MU32 MU15 PK B5, CS Terminus Mumbai


Swamy

ND48 ND50 S Tripathi 13, B1 D, MayurVihar New


Delhi

a. Create sender and recipient tables where senderid is foreign key.

b. Insert data as given above.

c. To display the names of all Senders from Mumbai.

d. To display the ReclD, SenderName, SenderAddress, RecName, RecAddress for every


Recipient.

e. To display Recipient details in ascending order of RecName.

f. To display number of Recipients from each city.

FUNCTIONS

function definition
Advantages

Function Types
(i) Built-in functions
- print,input,type,id,int,float,str,len,range,round
(ii) library function -
math(pi, e, sqrt, ceil, floor, pow, fabs, sin, cos, tan)
random(random,random()*(UB-LB)+LB, randint(LB,UB),randrange(start,sop,step)
statistics(mean(),median(),mode())

#-------------------------------------------------------------------------------------------------------------------------------------
----------------

(iii) user defined functions

Arguments/Parameters
Actual/Formal

Passing parameters
Positional
Default
Keyword

Returning Valued
void
Single
Multiple
Scope of variables
Local
Global
LEGB
Mutable/Immutable properties of passed data objects
Module Creation
help(modulename)
Calling of modules
import module
from module import functionname/*

Module : It is a container of functions. Ex: math,statistics,random

function
It is a named group of instructions to do a specific job.
It may or may not have arguments/parameters.
do processing
may or may not return value(s)

Ex:
print()
print('hi')
print('hi','bye',sep='$')

name = input('Enter a value ')

type()
id()
int()

Advantages:
1. Reusability
2. Save time
3. Save memory
4. Increase the understanding of program
5. Program development becomes easy and fast

Type of functions:
1. Built-in functions/Library- These are the functions which are by default available in Python.
print(), input(), type(),id(),int(),float(),str(),len(),range(),eval()

eval()
eval() - It takes a string as a parameter, evaluate this string as a number and
then returns the numeric result (int or float as the case may be)

x = eval('45+10')
print(x)

round(number,no_of_digits) - to round off the given value

print(round(3.141593))
print(round(3.141593,1))
print(round(3.141593,2))
print(round(3.141593,3))

2. Functions defined within module(It is a container of functions)


math module
sqrt(), pow(),floor(), ceil(),sin(),cos(),tan()

1. sqrt() - to return square root of given value.


import math
print(math.sqrt(81))

from math import * # all functions are included


print(sqrt(81))

from math import sqrt # sqrt function is included


print(sqrt(81))

2. pow(m,n) - to return the value after raising m to the power on n

import math
print(math.pow(3,4))

3. floor(value) - It will return the value i.e equal or lesser than the given value.

from math import *


print(floor(-2.75))

3. ceil(value) - It will return the value i.e equal or greater than the given value.

from math import *


print(ceil(-2.75))

print(11/4)
print(11//4) #integer division
print(11.0//4) #integer division- float / int - float
print(-11.0//4) #integer division

from math import *


print(floor(-2.75))

import statistics
L = [6,2,5,8,9,1,7,2]
print(statistics.mean(L))
from statistics import *
L = [6,2,5,8,9,1,7,2,3,4,2,3,6,7,3,4,2]
print(mode(L))

from statistics import median


L = [6,2,5,8,9,1,7,2,3,4,2,3,6,7,3,4,2]
L.sort()
print(median(L))

statistics module
mean(), median(), mode()
random module
random(),randint(),randrange(start,stop,step)

3. User defined functions


Syntax:

def Function_name(Arguments/Parameters): //function header


statements
return value(s)

def - keyword

#WAF to display 'Hello' with the name which is passed as parameter

def Display(Name):
print('Hello',Name)

Display('Rajesh')

#WAF to return Simple Interest of the values which are passed as parameter.
def SI(P,R,T):
si = (P*R*T/100)
return si

P = int(input('Enter P : '))
R = int(input('Enter R : '))
T = int(input('Enter T : '))

print('Simple Interest : ',SI(P,R,T))


Amount = P + SI(P,R,T)
print('Amount = ',Amount)
#-------------------------------------------------------------------------------------------------------------------------------------
----------

Computer Science(083)
Sample Question Paper - Set 1
● The paper contains three sections A, B and C
● All Questions are compulsory in all the sections

SECTION A

QNo 1 Select the device out of the following, which can not be used as a input device:
(a) Scanner
(b) JoyStick
(c) BarCode Printer
(d) RFID Reader

2 Select the device out of the following, which can not be used as a storage device:
(a) HDD
(b) Pen Drive
(c) WiFi Dongle
(d) DVD Drive

3 Arrange the following in ascending order as per the storage capacity:


GB, KB, TB, MB

4 Give two examples of Application software. 1


5 Which of the following icons represent System Software?
1
6 Which of the following character system is most appropriate for encoding the character
(a) PASCII (b) ASCII (c) ISCII (d) UNICODE
1
7 Write the equivalent value in bytes for 1 GB. 1
8 Find the invalid name for an identifier(s) in Python from the following :
(a) While (b) false (c) 4thCross (d) Value
1
9 Identify the valid arithmetic operator(s) used in Python out of the following.
(a) != (b) ** (c) in (d) or
1
10 Given the following declaration in Python
Rec ={"A":10,"B":21,"C":20,"D":19}
Select the correct output of:
for K in Rec: print(K,end="*")
(a) A*B*C*D*
(b) [A*B*C*D*]
(c) 10*21*20*19
(d) [10*21*20*19]
1
(a)
(b)
(c)
(d)
DELHI PUBLIC SCHOOL, R.K.PURAM, NEW DELHI
Page: 2/4
11 A dictionary is declared as
T = {1:100,2:"X","A":200,"B":"C"}
Which of the following statements will be incorrect if written immediately after
the above declaration of T?
(a) T["A"]+=5 (b) T["C"]+="D" (c) T[2]+="Y" (d) T[5]="D"
1
12 Select the correct output for the following Python code
Nums=(12,56,78,90,20,50)
print(Nums[::-2]+Nums[::2])
(a) (12, 78, 20, 50, 90, 56)
(b) [12, 78, 20, 50, 90, 56]
(c) (50, 90, 56, 12, 78, 20)
(d) [50, 90, 56, 12, 78, 20]
1
13 Which of the following best matches the type of declaration of Students :
S={101:'Amit',105:'Suraj',103:'Manan'}
Students = sorted(S.values())
(a) list (b) tuple (c) string (d) dictionary
1
14 Write the output for the following Python statement on execution:
print( 50 // 9 + pow(3, 2) * 2 - 5)
1
15 Name the built-in function / method that returns the nearest lower integer equivalent to
a float number. i.e. for 9.6, it should return 9
1
16 Which of the following options is not a characteristic of a Trojan Horse:
(a) It is a Malware
(b) It misleads users as a useful software
(c) It self replicates in a computer network
(d) Its name is derived from an ancient Greek story
1
17 Which of the following options cannot be categorized as an Intellectual Property:
(a) A dress designed by a designer
(b) A music composed by a musician
(c) A computer owned by a software engineer
(d) Design of a car produced by an automobile company
1
18 Which of the following is a correct example of Plagiarism :
(a) Sending bulk emails to someone
(b) Copying someone else’s project and submitting it as one’s own
(c) Insulting a person during an online chat
(d) Using someone’s login credentials to send fake email
1
19 Which of the following options is not a valid Open Source License:
(a) MIT (b) GNU (c) Oracle (d) Apache
1
20 A catfish is a term used in Online Scams for:
(a) A person who uses a fake online profile
(b) A malware used to steal login credentials
(c) A computer virus to stop working of a computer
(d) A website to deceive a user to provide Bank Accounts details
1
21 Which of the following is incorrect feature of Open Source Software:
(a) It is publicly accessible
(b) It’s code is available for modification
(c) Users can sell the modified code of such software
(d) It is modified by users for improving its features
1
DELHI PUBLIC SCHOOL, R.K.PURAM, NEW DELHI
SECTION B
Page: 3/4
22 Add the following binary numbers and write the steps and final result:
(a) (1101111) 2 +(10001111) 2 (b) (10101011) 2 +(11011101) 2
2
23 Draw a logic circuit equivalent for the following Boolean Expression:
X+Y’.Z
2
24 Write the output for the following Python statements on execution:
S=[(20,40,60),["A","B","C"],"PACKED"]
print(S[2][2:])
print(sorted(S[::-1][1],reverse=True))
2
25 Write the results of the following:
(a) (19+2>7+11) or (12//3 == 12/3)
(b) 13*2==(15-4//2) and (15-8)>(17*2)
2
26 Given the following Dictionary :
D = {1: "A" , 3: "B", 5: "C"}
Write a Python code to change the content of D as follows:
{1: "AA", 3: "BA", 5:"CA", 2: "X", 4:"X"}
2
27 Write a code to display sum of each adjacent pair of values of a list L with the following
content:
L=[10,20,30,40,50,60]
Output should be:
30
70
110
2
28 Rewrite the following logic using a while loop without making any change in the expected
output:
S=0
for C in range(20,10,-2):
print(C,end=",")
S+=C
print(S)
2
29 Rewrite the following code after removing all the syntax error with each of the
corrections underlined:
M=int(input("Enter M'))
while M<10
if M=5:
print("Middle Value")
Else:
print(M)
M+=1
2
30 Write a Python code to find the mode of values of the following list R containing integers
without using the builtin statistics module functions.
R=[12,45,65,45,56,45,12]
2
31 Differentiate between Mutable and Immutable data types in Python. Give suitable
examples of each.
2
32 Write any two differences between Cyber Troll and Cyber Bullying. 2
33 Write any two precautionary steps that we should follow to prevent ourselves from online 2
DELHI PUBLIC SCHOOL, R.K.PURAM, NEW DELHI
SECTION C
Page: 4/4
identity thefts.
34 Write a code in Python to display the first N values (N to be entered by user) of the
fibonacci series starting from 0 and 1.
Example:
N:6
011235
3
35 Find the output of the following code:
P=["AAMAR","JALAJ","JOHNY","PARAM","TALAT"]
for i in range(len(P)):
print(P[i][i:])
print(P[3])
3
36 Find the output of the following code:
N=13254;P=0
while N:
print(N)
P=P*10+N%10
N//=10
print(P)
3
37 Convert the following (Working steps to be shown along):
(a) (10111011) 2 = (____________) 8
(b) (11101011) 2 = (____________) 10
(c) (134) 8 = (____________) 16
(d) (2E5) 16 = (____________) 10
4
38 Write a python code
● To accept 9 integers from user in a list L
● To break up the content of the list L into 3 equal portions and store in three variables
L1, L2 and L3 as lists.
● To display the content as well as sum of the content of each L1, L2 and L3.
4
39 Write a Python code to accept Names of students from the user, store them in a list S.
Create a dictionary with the help of the list S, by assigning roll numbers from 1 to N as
keys along with values as Names of the students. Display the content of the dictionary.
4
40 Write a python code to accept values of X as float and N as int, find and display the sum
of following series:
(a) X + X 2 + X 3 + .... +X N
(b) X+X/2!+X/3!+ ....+X/N!
4
#-------------------------------------------------------------------------------------------------------------------------------------
------------

Computer Science(083)
Sample Question Paper Set - 2
● The paper contains three sections A, B and C
● All Questions are compulsory in all the sections
SECTION A
Page: 1/4
Maximum Marks: 70 Time Allowed: 3 Hours
QNo
1 Select the System Software out of the following :
(a) Anti Virus
(b) Device Drivers
(c) Google Document
(d) Inventory Control
1
2 Intermediate Object code is generated in case of :
(a) Binary
(b) Assembler
(c) Compiler
(d) Interpreter
1
3 1 PB = ___________ GB 1
4 Give two examples of Utility software. 1
5 The ASCII range for lower case alphabets(a to z) is ____ to _______. 1
6 Which of the following character systems encodes the main Indic scripts and a Roman
transliteration.
(a) PASCII (b) ASCII (c) ISCII (d) UNICODE
1
7 PASCII stands for:
(a) Perso-Arabic Script Code for Information Interchange
(b) Persian-Arabic Script Code for Information Interchange
(c) Pre-Arabic Script Code for Information Interchange
(d) Perso-American Standard Code for Information Interchange
1
8 Find the invalid name for (an) identifier(s) in Python from the following :
(a) Paper#1 (b) Else (c) 11thClass (d) for
1
9 Identify the valid logical operator(s) used in Python out of the following.
(a) != (b) ** (c) in (d) or
1
10 Write a statement in Python to declare a dictionary friends whose keys are 1, 2, 3,4
and values are Amit, Swati, Vishal and Neha respectively.
1
11 A tuple is declared as
T = (89,67,92,78,93)
Which of the following statements will be incorrect if written immediately after
the above declaration of T ? (a)print(T[1])
(b)T[2]=-29
(c)print(max(T))
(d)print(len(T))
1
DELHI PUBLIC SCHOOL, R.K.PURAM, NEW DELHI
SECTION B
Page: 2/4
12 Select the correct output for the following Python code :
Name="PYTHON"
print(Name[::-2]+Name[::2])
(a)NHYPTO
(b)YPTNHO
(c)PTNHYO
(d)NHYPHN
1
13 Select the correct output for the following Python code:
L=[1,2,3]
L*=3
print(L)
(a) [1,2,3]
(b) [3,6,9]
(c) [1, 2, 3, 1, 2, 3, 1, 2, 3]
(d) [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
1
14 Write the output for the following Python statement on execution:
print(2**5-round(2.678,1)*35//3)
1
15 Name the built-in function / method that returns the random integer in between start
value and end value
1
16 Which of the following options is not a characteristic of a Cyber Troll:
(a) Seek attention
(b) Shifts attention from the author's content and conversations to their own
(c) Makes a person famous in a positive way
(d) Want responses to their inflammatory comments from the original author
1
17 Which of the following is not a Malware:
(a) Trojan Horse
(b) Worms
(c) Spyware
(d) Norton AntiVirus
1
18 Another name for ‘spoofing’ is :
(a) Virus
(b) Phishing
(c) spam
(d) Adware
1
19 Which of the following options is not a valid Open Source Software:
(a) Python (b) Linux (c) MS Excel (d) MYSQL
1
20 Which of the following is incorrect for “unsolicited mail”:
(a) Unwanted bulk mail
(b) Digital Junk mail
(c) Send by fake or hacked emails
(d) Publicly accessible mailbox
1
21 Which of the following is incorrect feature for Digital rights management (DRM) :
(a) restrictive licensing agreements
(b) copyrighted works (such as software and multimedia content)
(c) Tools for access control technologies
(d) An important part of social networking websites.
1
DELHI PUBLIC SCHOOL, R.K.PURAM, NEW DELHI
SECTION C
Page: 3/4
22 Add the following binary numbers and write the steps and final result:
(a) (1001001) 2 +(10001000) 2 (b) (11111001) 2 +(101010101) 2
2
23 Draw a logic circuit equivalent for the following Boolean Expression:
X+(Y’.Z)
2
24 Write the output for the following Python statements on execution:
x=1
y=2
l1=[x+y]*5
l2=[x*1,x*2,x*3,x*4]
print(l1,l2)
2
25 Write the results of the following:
(a) not 15<2 or 2**3 > 12/3
(b) 6*5-14//7+2**3-pow(3,2,2)
2
26 A tuple is declared as
T=(10,20,30,20,30,40,30,40)
Display the frequency of each element as given in the Output below:
10 occurs 1 times
20 occurs 2 times
30 occurs 3 times
40 occurs 2 times
2
27 Create a string that stores the names of five classmates.Count and display the names that
start with vowels.
2
28 Rewrite the following logic using a while loop without making any change in the expected
output:
I=10
for C in range(1,5,2):
print (C)
I+=C
print("New Value of I is :",I)
2
29 Rewrite the following code after removing all the syntax error with each of the
corrections underlined:
y=int(input("Enter Y:")
if y<10
print('smaller")
Else:
print(y)
2
30 Write a Python code to store the string and integers in two different list from the given
tuple:
T=("Delhi",45,67,34,"Mumbai")
city=["Delhi","Mumbai"]
N=[45,67,34]
2
31 Differentiate between ceil() and floor() in Python. Give suitable examples of each. 2
32 Write any two differences between Phishing and Eavesdropping. 2
33 What is Intellectual Property Right (IPR)? Name any two types of IPR. 2
DELHI PUBLIC SCHOOL, R.K.PURAM, NEW DELHI
Page: 4/4
34 Accept a number from the user and check whether it is an Armstrong number or not. Print
appropriate messages.
Note: An Armstrong no. is one in which the sum of the cubes of the digits of a number is
equal to the number itself. For example,
153 = 13 + 53 + 33
3
35 Find the output of the following code:
m=""
s='Year21@Com'
for i in range(0,len(s)):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
print(m)
3
36 Find the output of the following code:
L=[]
for I in range(100, 150):
if (I%7==0) and (I%5!=0):
L.append(I)
print(L)
3
37 Convert the following (Working steps to be shown along):
(a) (625) 2 = (____________) 8
(b) (11001100) 2 = (____________) 10
(c) (8AF) 16 = (____________) 8
(d) (56DA) 16 = (____________) 10
4
38 Write a python code
● To input 10 integers into a list.
● Swap all the adjacent pairs of elements of the list.
● Remove all the even integers from the entered list and display the list (with only odd
integers).
● Display the list in the reverse order.
4
39 Write a Python code to concatenate two dictionaries D1 and D2 by adding the common
keys to form the dictionary D. Display D1, D2 and D.
For example: D1 = {0:5, 1:10}
D2 = {1:10,2:15, 3:20}
Then D should become: {0:5, 1:20, 2:15, 3:20}

D1 = {0:5, 1:10}
D2 = {1:10,2:15, 3:20}
D={}
N = len(D1)
M = len(D2)
k=0
while k<N or k<M:
v= D1[k] + D2[k]
D[k]=v
k = k+1

prin(D)

4
40 Write a python code to accept values of X as float and N as int, find and display the sum
of following series:
(a) 1+(1+3)+(1+3+5)+... upto N terms
(b) X+2X+3X+ ....upto N terms
4

#-------------------------------------------------------------------------------------------------------------------------------------
--------
Class XI Final Examination Session 2020-2021
Computer Science(083) Set - P6
(Theory)
● The paper contains three sections A, B and C
● All Questions are compulsory in all the sections
SECTION A
DPS RKP PURAM CS P6-SRMK#1 2021 PAGE: 1/4
Maximum Marks: 70 Time Allowed: 3 Hours
QNo
1 Select the device out of the following, which can not be used as a input device:
(a) Plotter
(b) JoyStick
(c) Scanner
(d) RFID Reader
1
2 Select the device out of the following, which can be used as a storage device:
(a) Modem
(b) Ram
(c) WiFi Dongle
(d) SSD
1
3 Arrange the following in descending order as per the storage capacity:
GB, KB, TB, MB
1
4 Give two examples of Application software. 1
5 Which of the following icons represent Utility Software?
1
6 Which of the following character system is most appropriate for encoding the character
(a) ASCII (b) UNICODE (c) PASCII (d) ISCII
1
7 Write the equivalent value in bytes for 1 TB. 1
8 Find the invalid name for an identifier(s) in Python from the following :
(a) for (b) false (c) 4thCross (d) _Value
1
9 Identify the valid Assignment operator(s) used in Python out of the following.
(a) != (b) == (c) = (d) >
1
10 Given the following declaration in Python
Rec ={"W":50,"X":45,"Y":95,"Z":96}
Select the correct output of:
for M in Rec: print(M,end="*")
(a) W*Z*Y*Z*
(b) [W*X*Y*Z*]
1
(a)
(b)
(c)
(d)
DPS RKP PURAM CS P6-SRMK#1 2021 PAGE: 2/4
(c) 50*45*95*96
(d) [50*45*95*96]
11 A dictionary is declared as
D = {1:10,2:"E","S":20,"B":"M"}
Which of the following statements will be incorrect if written immediately after
the above declaration of T?
(a) D ["S"]+=5 (b) D["M"]+="L" (c) D[2]+="N" (d) D[5]="P"
1
12 Select the correct output for the following Python code
Nums=(12,56,78,90,20,50)
print(Nums[::-2]+Nums[::2])
(a) (12, 78, 20, 50, 90, 56)
(b) [12, 78, 20, 50, 90, 56]
(c) (50, 90, 56, 12, 78, 20)
(d) [50, 90, 56, 12, 78, 20]
1
13 Which of the following best matches the type of declaration of Students :
P={10:'Ananya',11:'Prithvi',12:'Manasvi'}
Students = sorted(P.values())
(a) list (b) tuple (c) string (d) dictionary
1
14 Write the output for the following Python statement on execution:
print( 50 // 9 + pow(3, 2, 2) * 2 - 5)
1
15 Name the built-in function / method that returns a float number between 0 and 1. 1
16 Which of the following options is not a characteristic of a Worm:
(a) It is a Malware
(b) It misleads users as a useful software
(c) It self replicates.
(d)It often uses a computer network to spread itself,
1
17 Which of the following options cannot be categorized as an Intellectual Property:
(a) A dress designed by a designer
(b) A music composed by a musician
(c) A computer owned by a software engineer
(d) Design of a car produced by an automobile company
1
18 Which of the following is a correct example of Cyberbullying :
(a) Impersonation
(b) Copying someone else’s project and submitting it as one’s own
(c) Posting flame wars or intentionally upsets people on the Internet.
(d) Practice where an individual or group uses the Internet to ridicule, harass or harm
another person.
1
19 Which of the following options is not a valid Open Source License:
(a) AZURE (b) GNU (c) Firefox (d) Apache
1
20 A -------- is a term used in Online Scams for a person who uses a fake online profile 1
21 Which of the following is incorrect feature of Open Source Software:
(a) It is publicly accessible
(b) It’s code is available for modification
(c) Users can sell the modified code of such software
1
SECTION B
DPS RKP PURAM CS P6-SRMK#1 2021 PAGE: 3/4
(d) It is modified by users for improving its features
22 Add the following binary numbers and write the steps and final result:
(a) (1011111) 2 +(1100001) 2 (b) (10101011) 2 +(10110011) 2
2
23 Draw a logic circuit equivalent for the following Boolean Expression:
X’+ Y.Z’
2
24 Write the output for the following Python statements on execution:
L=[["A","B","C"],(20,40,60),"PACKED"]
print(L[2][2:])
print(sorted(L[::-1][1],reverse=True))
2
25 Write the results of the following:
(a) (18+2>6+11) and (not(10//2 == 10/2))
(b) 11*2==(17-4//2) or (15-8)>(7*1) and 15>5
2
26 Given the following Dictionary :
N = {10: "X , 30: "Y", 50: "Z"}
Write a Python code to change the content of as follows:
{10: "XX", 30: "YX", 50:"ZX", 20: "M", 40:"M"}
2
27 Write a code to find and display sum of values stored in the first half and the second half
values of a list T with the following content:
T=[70,10,50,20,60,30]
Output should be:
130
110
2
28 Rewrite the following logic using a for loop without making any change in the expected
output:
T=0;I=100
while I>20:
print(T,I,end=":")
T+=I
I-=20
print(T)
2
29 Rewrite the following code after removing all the syntax error with each of the
corrections underlined:
P=int(input('P?"))
while P>=10:
if P>25
print("High")
elseif P>15:
print("Middle")
else:
print(P)
P-=5
print("Over";P)
2
30 Write a Python code to find the mode of values of the following list S containing integers
without using the builtin statistics module functions.
S=[20,40,60,40,50,40,10]
2
31 Differentiate between logical and syntax errors. Give suitable examples of each using
Python code.
2
SECTION C
DPS RKP PURAM CS P6-SRMK#1 2021 PAGE: 4/4
32 Write any two differences between Trojan horse and Eavesdropping. 2
33 Write any two precautionary steps that we should follow to prevent ourselves from online
Phishing.
2
34 Write a code in Python to accept the value of an integer N, check if it is a Prime Number
or not, and display an appropriate message.
Example:
N:7
It is a Prime Number
3
35 Find the output of the following code:
T=('ABCDE',"START",'VWXYZ',"MNPQR","STOPS")
N=len(T)
ST=""
for C in range(N-1,0,-1):
print(T[N-C][C:])
ST+=T[N-C][C]
print(ST)
3
36 Find the output of the following code:
L=[1,7,2,5,4];S=0;I=0
while L[I]!=4:
S+=2*L[I]
if I%2==0:print(L[I],S)
I+=1
else:
print(L[I],end="#")
print(S)
3
37 Convert the following (Working steps to be shown along):
(a) (432) 8 = (____________) 16
(b) (11001001) 2 = (____________) 10
(c) (10101111) 2 = (____________) 8
(d) (B27) 16 = (____________) 10
4
38 Write a python code
● To accept 8 integers from user and store them in a list L
● To create two lists from L as L1 and L2 with L1 containing the last four values of L and
L2 containing the first four values of L in the reverse order.
● To display the content as well as sum of the content of each L1 and L2.
4
39 Write a Python code to accept Names of 5 cities from the user, store them in a list C.
Create a dictionary with the help of the list C, accepting and assigning cities’ capitals as
values with corresponding Keys from C. Display the content of the dictionary.
4
40 Write a python code to accept values of U as float and N as int, find and display the sum
of following series:
(a) 2 + (2+4)+ (2+4+6)+ .... + (2+4+6+...2*N)
(b) U+U 2 /2+U 3 /3+ ....+U N /N
4

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Parameters- These are the variables/values given to the function.


These are of two types:
1. formal parameters - which are given in the function declaration/definition.
Their values are not known beforehand.
2. actual parameters - which are given at the time of calling the function.

#---------------------------------------------------------------------------------
WAF to find area and perimeter of a rectangle.
#---------------------------------------------------------------------------------

def Rectangle(): #function definition/header


length = int(input('Enter Length : '))
breadth = int(input('Enter Breadth : '))

area = length * breadth


perimeter = 2 * (length + breadth)

print('Area = ',area,'and perimeter = ',perimeter)

Rectangle()
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
WAF to find display of first N natural numbers, where N is passed as parameter.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------

def Display(N):
for k in range (1,N+1,1):
print (k,end=' ')

N = int(input('How many natural Numbers : '))


Display(N)

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
#WAF to find N is odd or even, where N is passed as parameter.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
def ODD(N):
if N%2==0:
print(N,' is even number')
else:
print(N,' is odd number')

ODD(11)
ODD(10)

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
WAF to find factorial of a number which is passed as parameter.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------

def Factorial(n):#function definition/header - n - formal parameter


f=1
for k in range(1,n+1,1):
f=f*k
print('Factorial of ',n,'=',f)
#---------------------------------------------------------------------------------
Factorial(5) # 5 - actual parameter
#---------------------------------------------------------------------------------

arguments/parameter

Values or variables which are provided at the time of defining or calling the function.

These are of following types

Formal arguments actual argumnets


#-------------------------------------------------------------------------------------------------------------------------------------
----------------
1. which are provided at the defining time 1. which are provided at the time of calling the function
2. Their values are not known beforehand 2. Their values ara known.
3. It is an identifier. 3. These may be value/variable or expression.
Ex:
def Area(length, breadth): # formal parameters
area = length * breadth
print(area)

Area(5) # actual parameter


#-------------------------------------------------------------------------------------------------------------------------------------
----------------

WAF to return factorial of a number which is passed as parameter.


#-------------------------------------------------------------------------------------------------------------------------------------
----------------
def Factorial(n):#function definition/header and n is formal argument
f=1
for k in range(1,n+1,1):
f=f*k
return f

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
WAF to display factors of anumber which is passed as parameter.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
def Factors(n):#function definition/header and n is formal argument
for k in range(1,n+1,1):
if n%k==0:
print(k)

#-----------------------Main--------------------------------------------------------------------------------------------------------
------------

print('factorial of 5 = ',Factorial(5)) # 5 is actual argument

N = int(input('Enter a number : '))


print('factorial of ',N,'= ',Factorial(N)) # N is actual argument

Factors(N)
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
Write a Menu Driven program to do the following operations on a number :
1. Factorial
2. Factors
3. Exit
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
def Factorial(n):#function definition/header and n is formal argument
f=1
for k in range(1,n+1,1):
f=f*k
return f
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
def Factors(n):#function definition/header and n is formal argument
for k in range(1,n+1,1):
if n%k==0:
print(k)
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
choice = 0
while choice!=3:
print('\n\nM E N U \n')
print('1. Factorial')
print('2. Factors')
print('3. Exit')

choice = int(input('Select Your Choice [1/2/3] : '))


if choice==1:
N = int(input('Enter a number : '))
print('factorial of ',N,'= ',Factorial(N))
elif choice==2:
N = int(input('Enter a number : '))
print('factors of ',N,':')
Factors(N)
elif choice==3:
print('\nExit the Program............')
else:
print('\nInvalid Choice, Retry 1/2/3')
#-------------------------------------------------------------------------------------------------------------------------------------
------
6. Write a program with a user-defined function with string as a parameter which replaces all vowels in the
string with ‘*’.

#-----------------------------------------------------------------------------------------------------------------------------
--------------
def strep(str):
str_lst =list(str) # convert string into list

# Iterate list

for i in range(len(str_lst)):

# Each Character Check with Vowels

if str_lst[i] in 'aeiouAEIOU':

# Replace ith position vowel with'*'

str_lst[i]='*'

#to join the characters into a new string.

new_str = "".join(str_lst)
return new_str

def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
#-------------------------------------------------------------------------------------------------------------------------------------
-------
global keyword
It allows the programmer to modify the variable outside the current scope.
It is used to create a global variable and make changes to the value in local context.
A variable declared inside a function is by default local and a variable declared outside the functio is
global by default.
global keyword is wriiten inside the function to use its global value. Outside the function, global
keyword has no effect.
Ex:
a= 10
def add():
global a
a = a+2
print('inside function a - ',a)

add()
a = 15
print('in main a -',a)

inside function a - 12
in main a - 15

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
WAF to display first N prime numbers, where N is passed a parameter.
N-8 - 2,3,5,7,11,13,17,19
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
for k in range(2,N//2+1):
if N%k==0:
print(N,'is not prime')
break
else:
print(N,'is prime')

def Isprime(N): #function definition


a=1
b=2
while a<=N:
factors = 0
for k in range(1,b+1):
if b%k==0:
factors += 1
if factors == 2:
print(b,end=' ')
a=a+1
b=b+1

n = int(input('How many prime numbers : '))


Isprime(n) #function calling
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
#WAP to return reverse of a number which is passed as parameter.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
#WAF to display the following series upto N terms, where N is passed as parameter.
0 1 1 2 3 5 8 13 21...................................N terms (fibonacci series

def Fibonacci(N):
first = 0
second = 1
for k in range(N):
print(first,end = ' ')
first,second = second,first+second

N = int(input('How many Terms ? '))


Fibonacci(N)

WAF to retrun the product of all digts in a number, where number is passed as parameter.

WAF to assign car and house according to Designation which is passed as argument
Designation Car House

Director BMW Bunglow


Manager/Executive CIAZ MIG
Accountant DZIRE LIG

#---------------------------------------------------------------------------------
Designation = input('Enter Your Designation : [Director/Manager/Executive/Accountant]')
car,house = car_house(Designation)
print('Car : ',car,'and house : ',house)

def SI(p,r,t):
si = (p*r*t)/100
return si

#-----------------------------------------------------------------
principle = int(input('Enter Priciple amount : '))
rate = int(input('Enter Rate of Interest : '))
time = int(input('Enter Time : '))

interest = SI(principle,rate,time)

amount = principle + interest

print('Simple Interest : ',interest)

print('Total Amount : ',amount)

def SI(p=5000,r=10,t=5): #function header


si = (p*r*t)/100
return si

#-------------------------------------------
print('Simple Interest = ',SI(1000,5,2)) #calling
print('Simple Interest = ',SI(1000,5)) #calling t = 5
print('Simple Interest = ',SI(1000)) #calling t = 5 r = 10
print('Simple Interest = ',SI()) #calling p - 5000 r = 10 t = 5

print('Simple Interest = ',SI(r=5,p=100,t=9)) #keyword arguments

WAF to display the following pattern:

A
AB
ABC
ABCD
ABCDE

for a in range(65,70):
for b in range(65,a+1,1):
print(chr(b),end='')
print()

ord = to return ascii value of given symbol.

Name = 'Krishna Dev'


for k in Name:
print(k,ord(k))

A
AB
ABC
ABCD
ABCDE

for r in range(65,70,1):
for c in range(65,r+1,1):
print(chr(c),end='')
print()

WAF to input three sides of a triangle and check whether a triangle is possible or not.
If possibe, then display it is an Equilateral, an Iso-sceles or a Scalene triangle,
display "Triangle is not possible".

def Triangle():
a = int(input('Enter first side of triangle : '))
b = int(input('Enter second side of triangle : '))
c = int(input('Enter triangle side of triangle : '))
if a+b>c and b+c>a and c+a>b:
print('Triangle is possible')
if a==b and b==c and c==a:
print('Triangle is Equilateral')
elif a==b or b==c or c==a:
print('Triangle is Isosceles')
elif a!=b and b!=c and c!=a:
print('Triangle is Scalene')
else:
print('Triangle is not possible')

Triangle()

Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).

import random

def roll_dice():
print (random.randint(1, 6))

print("Welcome to my python random dice program!


To start press enter! Whenever you are over, type quit.")

flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()

#----------------------------------------------------------------------------------
PRACTICAL LIST - 2
#----------------------------------------------------------------------------------
1 Define a function Isprime( ) that returns 1 if the value passed to its parameter is a prime integer otherwise it
returns 0.
Use this function in the program to display all prime numbers between 1 and 100.

#----------------------------------------------------------------------------------

2 Define a function Div2( ) that returns 1 if n is divisible by 2 otherwise it returns 0, and Div3( ) that returns 1
if n is divisible by 3 otherwise it
returns 0. Use these functions in the program to check whether a number NUM is divisible by both 2 and 3 or
not.
#----------------------------------------------------------------------------------

3 Define a function Factorial ( ) that returns the factorial of the integer passed to its parameter.
Use this function in the program to display the sum of the following series:
1! + 2! + 3! + 4! +……………... upto N terms (where value of N is entered by the user)
#----------------------------------------------------------------------------------

4 Define a function Power ( ) that returns the result of x^y by passing x and y
as parameters . Use this function in the program to enter values of T and N and
display the sum of the following series:
T + T^2 + T^3 + T^4 +……………...upto N terms

#----------------------------------------------------------------------------------
5 Define a function Reverse ( ), that returns the reverse of the integer passed to
its parameter. Use this function in the program to display whether an integer
entered by the user is a Palindrome or not.

Note: A palindrome integer is a number which is same as its reverse,


example: 1221, 13531, 24342 etc.

#----------------------------------------------------------------------------------

6 Define a function Sum( ) that returns the sum of digits of an integer passed to its parameter.
For example if the integer passed is 2134, then the function should return 10 (i.e. the result of 2+1+3+4).
Call this function and display sum of digits of three different integers entered by the user.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
7 Define a function LCM( ) , that returns the LCM of the two integers passed to its parameter.
Use this function in a program to enter 3 integers and display their LCM.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------

def LCM(a,b):
BIG = max(a,b)
while BIG%a!=0 or BIG%b!=0:
BIG=BIG + 1
return BIG
#----------------------------------------------------
fno = int(input('Enter First Number : '))
sno = int(input('Enter Second Number : '))
tno = int(input('Enter Third Number : '))
print('LCM = ',LCM(LCM(fno,sno),tno))

8 Define a function HCF( ), that returns the HCF of the two integers passed to its parameter. Ex: 30 and 100
Use this function in a program to enter 3 integers and display their HCF.
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
def HCF(a,b):
for k in range(1,min(a,b)+1,1):
if a%k==0 and b%k==0:
hcf=k
return hcf
#----------------------------------------------------
fno = int(input('Enter First Number : '))
sno = int(input('Enter Second Number : '))
tno = int(input('Enter Third Number : '))
print('HCF = ',HCF(HCF(fno,sno),tno))

9 Define functions to make following patterns, for N number of lines (value of N to be passed to the function
parameter):
(a) 1 2 3
12
1

(b) 1
12
123

(c) 111
22
3
Call these functions in the main program and find results with the help of appropriate menu driven options.

10 Define functions to find sum of following series:


(i) X+X^2 + X^3 +............ + X^N (use int N and float X as parameters)
(ii) U+ U^2/2!+ U^3/3!+...……… + U^N/N! (use int N and float U as parameters)
(iii) X+2*X+3*X+... +N*X (use int N and float X as parameters)
(iv) 1 - 2!/U^2 + 3!/U^3 - 4!/U^4 ...……… + N!/U^N (use int N and float U as parameters)
Call these functions in the main program and find results sum of various series with the help of appropriate
menu driven options.
—--------------------------------------------------------------------------------------------------------------------
Exception Handling

bug - error

Debugging -

The process of finding errors, rectifying them, and recompiling the code until it becomes error free is termed as
debugging.

Errors are the problems in a program due to which the program will stop the execution or giveving incorrect
output.

Error in Python can be of two types i.e. Syntax errors and Exceptions (Run-time errors).

Syntax Errors :

These are the errors which occurs when you violate the rules of writing syntax (due to grammatical mistakes).

Ex: missing parenthese (), missing :

# initialize the amount variable


amount = 10000

# check that You are eligible to

if(amount>2999) #error :
print("You are eligible to get discount")

Exceptions:

Exceptions are raised when some internal events occur which changes the normal flow of the program.

Exceptions are raised when the program is syntactically correct but the code resulted in an error.
This error does not stop the execution of the program, however, it changes the normal flow of the program.

Example:

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)

#-------------------------------------------------------------------------------------------------------------------------------------
-----------
Exception Handling:
#-------------------------------------------------------------------------------------------------------------------------------------
-----------

What is Exception?

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the
program's
instructions.

When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.

Handling an exception

If you have some suspicious code that may raise an exception, you can defend your program by placing the
suspicious code in a
try: block.

After the try: block, include an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement:

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The try block will generate an exception, because x is not defined:

If i will write
print(x)

then output is

Traceback (most recent call last):


File "D:\Backup\Deepak Sharma Online Classes\online CS class.py", line 3472, in <module>
print(x)
NameError: name 'x' is not defined

But i want that a meaningful message shoul appear, so i will write code as :

try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a
special kind of error:

Print one message if the try block raises a NameError and another for other errors:

try:
print(x)
except NameError:
print("Variable x is not defined")

else:

1. NameError : when an identifier is not found


2. ZeroDivisionError: integer division or modulo by zero
3. IndexError: Invalid index value given
4. TypeError - when invalid type of data is given
5. IndentationError - Raised due to incorrect indentation

a = [1, 2, 3]
try:
print ("Second element = ",a[1])

# Throws error since there are only 3 elements in list

print("Fourth element = ",a[3])


except IndexError:
print "An error occurred"

You can use the else keyword to define a block of code to be executed if no errors were raised:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

Raise an error and stop the program if x is lower than 0:

Example :
x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example
Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")
#What will following python code produce, justify your answer :

x=5
y=0
print ('A',end='@')
try :
print ('B',end='#')
a=x/y
print ('C',end='^')
except ZeroDivisionError:
print ('F',end='&')
except :
print ('D',end='%')

PRACTICAL LIST – 7 (CBSE)

1. Input a welcome message and display it.

print('Welcome')

2. Input two numbers and display the larger / smaller number.

firstno = int(input('Enter First No : '))


secondno = int(input('Enter Second No : '))

if firstno>secondno:
print('Larger No : ',firstno)
else:
print('Larger No : ',secondno)

if firstno<secondno:
print('Smaller No : ',firstno)
else:
print('Smaller No : ',secondno)

output

Enter First No : 67
Enter Second No : 87
Larger No : 87
Smaller No : 67
3. Input three different numbers and display the largest / smallest number.

firstno = int(input('Enter First No : '))


secondno = int(input('Enter Second No : '))
thirdno = int(input('Enter third No : '))

if firstno>secondno and firstno>thirdno:


print('Largest No : ',firstno)
elif secondno>thirdno and secondno>firstno:
print('Largest No : ',secondno)
else:
print('Largest No : ',thirdno)

if firstno<secondno and firstno<thirdno:


print('Smallest No : ',firstno)
elif secondno<thirdno and secondno<firstno:
print('Smallest No : ',secondno)
else:
print('Smallest No : ',thirdno)

output

Enter First No : 8
Enter Second No : 4
Enter third No : 13
Largest No : 13
Smallest No : 4

4. Given two integers x and n, compute xn.


a. With exponent operator
b. With pow( ) function of math module
c. Without exponent and pow( ) function

from math import pow

x = int(input('Enter the value of x : '))


n = int(input('Enter the value of n: '))

print('With exponent operator X^n : ',x**n)


print('With pow( ) function of math module X^n : ',pow(x,n))

result = 1
for k in range(n):
result = result * x
print('Without exponent and pow( ) function x^n = ',result)

output

Enter the value of x : 4


Enter the value of n: 3
With exponent operator X^n : 64
With pow( ) function of math module X^n : 64.0
Without exponent and pow( ) function x^n = 64

5. Write a program to input the value of x and n and print the sum of the following series:
(a) 1+x+x2+x3+x4+.............xn

x = int(input('Enter the value of x : '))


n = int(input('Enter the value of n: '))
sum = 0
for k in range(0,n+1,1):
sum = sum + x**k

print('Sum of series : ',sum)

output

Enter the value of x : 2


Enter the value of n: 5
Sum of series : 63

(b). 1-x+x2-x3+x4-.............xn

x = int(input('Enter the value of x : '))


n = int(input('Enter the value of n: '))
sum = 0
sign = 1
for k in range(0,n+1,1):
sum = sum + (x**k)*sign
sign = sign * -1
print('Sum of series : ',sum)

output
Enter the value of x : 2
Enter the value of n: 5
Sum of series : -21

(c) -x + x2 - x3 + x4 - .............xn

x = int(input('Enter the value of x : '))


n = int(input('Enter the value of n: '))
sum = 0
sign = -1
for k in range(1,n+1,1):
sum = sum + (x**k)*sign
sign = sign * -1
print('Sum of series : ',sum)

output
Enter the value of x : 3
Enter the value of n: 4
Sum of series : 60

10. Determine whether a number is a perfect number, an Armstrong number or a palindrome.


11. Input a number and check if the number is a prime or composite number.
12. Display the terms of a Fibonacci series.
13. Compute the greatest common divisor and least common multiple of two integers.
14. Count and display the number of vowels, consonants, uppercase, lowercase characters in string.
15. Input a string and determine whether it is a palindrome or not; convert the case of characters in a string.
16. Find the largest/smallest number in a list/tuple.
17. Input a list of numbers and swap elements at the even location with the elements at the odd location.
18. Input a list of elements, sort in ascending/descending order.
19. Input a list/tuple of elements, search for a given element in the list/tuple.
20. Input a list of numbers and test if a number is equal to the sum of the cubes of its digits. Find the smallest
and largest such number from the given list of numbers.
21. Create a dictionary with the roll number, name and marks of n students in a class and display the names
of students who have marks above 75.

—------------------------------------------------------------------------------------------------------------------

File definition
Need for files
modes of file - r,w,a,r+
How to open file?
file_object = open(filename,mode)
Absulute and Relative path
How to close the file?
file_object.close()

File

It is a collection of bytes (alphabets, digits, special letters) to store information about a specific topic.
Ex. student file, employees file

Need: to store information for later user.

Type of files:

1. Text file
2. Binary file
3. CSV file (Comma Seprated Values)

Text file

It stores the information in the form of ASCII or Unicode characters. [Human readable format]
Each line of text is terminated by special character known as EOL(End of Line) [By default it is '\n']
Some internal translations take place when this EOL character is read or written.

extenstion - .txt
.rtf (Rich text format] wordpad
.doc (document) word

Q. How to open file?

File_Object = open(filename,mode)

filename - name of file to refer for later use

mode: What you want to do with file

r - read the file - by default


It will provide error FileNotFoundError if file not exist

w - write the data in file


It will create the file if not exist otherwise overwrite the contents

a - append
It will add the data in the end of file(previous data remains unchanged)
if not exist then create a new file

r+ - to read and write the data in file (modification)


Q. How to close the file?

file_object.close()

Q. How to write data in file ?

1) write() - method is used to write a string in the file.

Syntax:
File_object.write(string)

2) writelines() - method is used to write a list of strings in the file.

Syntax:
File_object.writelines(List)
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
Q. WAP to create a text file friends.txt and then store name of any 5 friends in it.
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
f = open('friends.txt','w')

f.write('Raj kumar\nPriya Rani\nSimmi\nDilip Kumar\nGeeta')

f.close()

#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
Q. Wow to read the contents of file?
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
1) read(n) - to read n characters from file. but if n is not specified then it will read all the contents.

Syntax :

File_object.read(n)

2) readline() - to read a complete line from file (till \n )

Syntax :

File_object.readline()

3) readlines(n) - to read all the lines and then return a list of lines. If n is given then only n lines.
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
Q WAP to display the contents of a text file "friends.txt".
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------

f = open('friends.txt')

data = f.read()
print('Contents of file : ',f.name) #name ,closed, mode atrributes
print(data)
f.close()

#-------------------------------------------------------------------------------------------------------------------------------------
-----------------

def Create():
f = open('friends.txt','w')
f.write('Raj kumar\nGeeta Verma\nSita Sharma\nPriya Devi\nSimmi Sachdeva')
f.close()

def Display():
try:
f = open('friends.txt','r')
data = f.read()
print('Contents of File : ',f.name)
print(data)
except FileNotFoundError:
print('File not found...............')

#WAF to add a friend name in the text file "Friends.txt".


def Append():
f = open('friends.txt','a')
f.write('\nDilip')
f.close()

while True:
choice = int(input('1. Create 2. Display 3. Append 4. Exit : '))
if choice==1:
Create()
elif choice==2:
Display()
elif choice==3:
Append()
elif choice==4:
print('Exit the program..................')
break #terminate the loop
else:
print('Invalid Choice, Retry 1/2/3/4')

#-------------------------------------------------------------------------------------------------------------------------------------
----
WAP to create a text file "Items.txt" and then store Ino,IName,Unit_Price and Qty in it , till user wants to store.

#WAF to find how many vowels in a text file 'friends.txt'

def Count_Vowels():
try:
f = open('friends.txt','r')
vowels = 0
data = f.read()
for k in data:
if k in 'aeiouAEIOU':
vowels += 1
f.close()
print('No. of vowels in file : ',vowels)
except FileNotFoundError:
print('No such file exist........................')

#WAF to find how many capital letters, small letters and digits in a text file 'friends.txt'

#WAF to find how many capital letters in a text file 'friends.txt'.

#WAF to create a text file "students.txt" to store a number of students names in it,till user wants to store.

def Create():
f = open('students.txt','w')
while True:
Name = input('Enter Student Name : ')
f.write(Name)
choice=input('Continue Y/N ? ')
if choice in ('n','N'):
break
f.close()

#WAF to display the contents of a text file "students.txt"

#WAF to display the contents of a text file whose name is passed as parameter.

def Display(fname):
f = open(fname)
data = f.read()
print('Contents of file',f.name)
print(data)
f.close()

Display('students.txt')

#--------------------------------------------------------------------------------------------------------------------
#WAF to add more students names in an existing text file "students.txt".
#--------------------------------------------------------------------------------------------------------------------
#WAF to find and display how many digits are in a text file "students.txt".

def Count_Digits():
f = open('students.txt')
data = f.read()
digits = 0
for k in data:
if k>='0' and k<='9': #if k.isdigit(): if k>48 and k<=57:
digits += 1

print('No. of Digits in file',f.name,' : ',digits)


f.close()

Count_Digits()
#--------------------------------------------------------------------------------------------------------------------------------
#WAF to find and display how many small letters and how many capital letters are in a text file "students.txt".
#-------------------------------------------------------------------------------
def Count_Letters():
f = open('students.txt')
data = f.read()
capital,small = 0,0
for k in data:
if k>='A' and k<='Z': #if k.isupper(): if k>65 and k<=90:
capital += 1
elif k>='a' and k<='z': #if k.islower(): if k>97 and k<=122:
small += 1

print('No. of Capital letters in file',f.name,' : ',capital)


print('No. of Small letters in file',f.name,' : ',small)
f.close()

Count_Letters()

#-------------------------------------------------------------------------------------------------------------------------------------
--------
#WAF to find and display how many "is" words are in a text file "students.txt".
#-------------------------------------------------------------------------------------------------------------------------------------
-------

def Create():
f = open('students.txt','w')
f.write('raj is my is priya is')
f.close()

def Display():
with open('students.txt') as f:
print(f.read())

def Count_is():
try:
f = open('students.txt')
data = f.read()
count = 0
for k in data.split():
if k=='is':
count += 1
print('\nNo. of "is" in file',f.name,' : ',count)
f.close()
except FileNotFoundError:
print('File not found')

Create()
Display()
Count_is()

Count_is()

#-------------------------------------------------------------------------------------------------------------------------------
#WAF to find and display how many words are of 2 letters in a text file "students.txt".
#------------------------------------------------------------------------------------------------------------------------------------

def Count_2():
f = open('students.txt')
data = f.read()
count = 0
for k in data.split():
if k.isalpha():
if len(k)==2:
count += 1
print('\nNo. of words which are of 2 letters in file',f.name,' : ',count)
f.close()
Count_2()

#WAF to display the contents of a text file 'friends.txt'.


#WAF to display the n characters of a text file 'friends.txt', where n is entered by user.
#WAF to add a friend name in the existed text file 'friends.txt'.
#WAF to create a text file 'xyz.txt'and then add a set of lines in it.
#WAF to find and display how many vowels are in a text file 'xyz.txt'.

#WAF to display each word terminated by * of a text file 'xyz.txt'.

#WAF to reverse and display each line of text file 'xyz.txt'.

def Reverse_lines():
try:
with open('friends.txt') as f:
data = f.readlines() # returns a list of lines
for k in data:
print(k[::-1],end='')
except FileNotFoundError:
print('File not found')

Reverse_lines()

#WAF to count alphabets, digits and spaces of a text file 'xyz.txt'.

#WAF to display lines ending with 'y' or 'Y' of a text file 'xyz.txt'.
if k[-2] in 'yY':
print(k)

tell()
returns an integer giving the file object's current position in the file,
measured in bytes from the beginning of file.
<file_object>.tell()

f.tell()

seek()
It is used to change the file object position and does not return any value.
<file_object>.seek(offset)

#----------------------------------------------------------------------------------
def Create():
f = open('friends.txt','w')
f.write('Raj\nGeeta Devi\nSita\nPriya\nSimmi')
f.close()

#----------------------------------------------------------------------------------

def Display():
f = open('friends.txt')
data = f.read()
print('Contents of file',f.name)
print(data)
f.close()

#----------------------------------------------------------------------------------

#WAF to display the longest line in file 'friends.txt'


def Longest_Line():
f = open('friends.txt')
data = f.readlines()
longest=' '
for k in data:
if len(k)>len(longest):
longest=k
print('Longest line : ',longest)

Create()
Display()
Longest_Line()

#------------------------------------------------------------------------------------

#WAF to display 5 letters from 6th letter of a text file 'friends.txt'.

#----------------------------------------------------------------------------------
def Display_5():#Display 5 letters from 6 letter
f = open('friends.txt')
f.seek(5)
data = f.read(5)
print('Last 5 leters of file',f.name)
print(data)
f.close()
#----------------------------------------------------------------------------------
#WAF to replace all occurences of 'a' with 'b' of a text file 'friends.txt'.
#----------------------------------------------------------------------------------
def Replace():
f = open('friends.txt','r+') # read and write
ch = f.read(1) #read first letter
while ch!='':
if ch=='a':
f.seek(f.tell()-1)
f.write('b') #overwrite
f.seek(f.tell())
ch = f.read(1)

f.close()

#-------------------------------------------------main----------------------

Create()
Display()

Display_5()

Replace()
print('After change file is :')
Display()

#WAF to replace lower to uppercase and upper to lowercase of a text file 'xyz.txt'.
#WAF to display alternate lines of a text file 'xyz.txt'.
#WAF to display the contents of a text file 'xyz.txt' in reverse(i.e first line first').

def Create():
f = open('xyz.txt','w')
choice='y'
while choice=='y':
s = input('Enter a line : ')
f.write(s)
choice = input('Do you want to add more y/n : ')
f.close()

#WAF to display the contents of a text file whose name is passed as an argument.

def Display(filename):
f = open(filename)
data = f.read()
print(data)
f.close()

#WAF to add add in the existed text file whose name is passed as argument.
def Add(filename):
f = open(filename,'a')

choice='y'
while choice=='y':
s = input('Enter a line to add in file : ')
f.write(s)
choice = input('Do you want to add more y/n : ')
f.close()

Write a Menu driven program to do the following operations:


1. New File
2. Display
3. Add in file
4.Exit
------------------------------------------

while True:
print('1. New file 2. Display 3. Add in the file 4. Exit')
choice = int(input('Enter your Choice [1/2/3/4] :'))
if choice==1:
Create()
elif choice==2:
Display('xyz.txt')
elif choice==3:
Add('xyz.txt')
elif choice==4:
print('Exiting the program...........')
break
else:
print('Invalid choice')

def fun():
f = open('story.txt','r')
f1 = open('alpha.txt','w')
f2 = open('digits.txt','w')
f3 = open('other.txt','w')

data = f.read()
for k in data:
if k.isalpha():
f1.write(k)
elif k.isdigit():
f2.write()
else:
f3.write()
f.close()

#Write a function countline( ) to count the number of lines containing a


#file article.txt.

def Create():
f = open('article.txt','w')
f.write('We are in class XII-B\n')
f.write('We are in science section\n')
f.write('Time is a great teacher\n')
f.write('India is great country')
f.close()

def count_lines():
f = open('article.txt')
data = f.readlines()
print('No. of lines in file ',f.name,'=',len(data))
f.close()

#Write a function display( ) which reads a file story.txt and display all those
#words in reverse order which are started with ‘I’ letter.

def display():
f = open('article.txt')
data = f.read()
for k in data.split():
if k[0] in ('I','i'):
print(k[::-1],end = ' ')
f.close()
#------------------------------------------------------------------------------------
#Write a function countuser( ) to count and search number of words entered by
#user containing a file story.txt.
#------------------------------------------------------------------------------------

def display():
f = open('article.txt')
data = f.read()
count=0
word = input('Enter a word to serach in file : ')
for k in data.split():
if k==word:
count += 1
print(word,'occurs',count,'times')
f.close()

#------------------------------------------------------------------------------------

Create()
count_lines()
display()
#------------------------------------------------------------------------------------
Find the output of the following:
#------------------------------------------------------------------------------------
Find the output of the following:

fo = open("myfile.txt", "w")
seq="Python\nWith MySQL!!"
fo.writelines(seq )
fo.close()

fo = open("myfile.txt", "r")
r=fo.read()
t=r.split()
for x in t:
print(x,end='%')
fo.close()

#----------------------------------------------------------------------------------
Python%With%MySQL!!%
#-----------------------------------------------

def Create():
with open('s.txt','w') as f:
f.write('raj kumar')

def countconsonants():
f=open('s.txt','r')
data=f.read()
count=0
for k in data:
if k.isalpha():
if k not in 'aeiouAEIOU':
count=count+1
f.close()
print('No. of consonants in file:',count)

Create()
countconsonants()

Write a program that accepts a filename of a text file and reports the file's longest line.

def get_longest_line(filename):
large_line = ''
large_line_len = 0

with open(filename, 'r') as f:


for line in f:
if len(line) > large_line_len:
large_line_len = len(line)
large_line = line

return large_line

filename = input('Enter text file Name: ')


print (get_longest_line(filename+".txt"))

Q. Remove all the lines that contain the character `a' in a file and write it to another file

f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()

f2 = open("copyMydoc.txt","r")
print(f2.read())

PRACTICAL LIST – 3
Text File
1. WAP to create a text file 'friends.txt' and then write name of any 5 friends in it.
2. WAF to display the contents of a text file whose name is passed as parameter.
3. WAF to display the n characters of a text file 'friends.txt', where n is entered by user.
4. WAF to create a text file "students.txt" to store a number of students names in it, till user wants to store.
5. WAF to add more students names in an existing text file "students.txt".
6. WAF to find and display how alphabets, many small letters, capital letters, digits and spaces are in a text file
"students.txt".
7. WAF to find and display how many vowels are in a text file "students.txt".
8. Write a function copy( ) which reads a file story.txt and copy all the alphabets in alpha.txt, all the digits in
digit.txt and other characters in other.txt.
9. WAF to find and display how many "is" words are in a text file "students.txt".
10. WAF to find and display how many words are of 4 letters in a text file "students.txt".
11. WAF to display each word terminated by * of a text file 'xyz.txt'.
12. Write a function display( ) which reads a file story.txt and display all those words in reverse order which are
started with ‘I’ letter.
13. Write a function countuser( ) to count and search number of words entered by user containing a file story.txt.
14. WAF to reverse and display each line of text file 'xyz.txt'.
15. WAF to display lines ending with 'y' or 'Y' of a text file 'xyz.txt'.
16. Write a function countline( ) to count the number of lines containing a file article.txt.
17. WAF to display 5 letters from 6th letter of a text file 'friends.txt'.
18. WAF to replace all occurences of 'a' with 'b' of a text file 'friends.txt'.#WAF to replace lower to uppercase
and upper to lowercase letters of a text file 'xyz.txt'.
19. WAF to display alternate lines of a text file 'xyz.txt'.

def Alternate():
with open('xyz.txt') as f:
data = f.readines()
for k in range(0,len(data),2):
print(k)

20. WAF to display the contents of a text file 'xyz.txt' in reverse (i.e first line first').

21. Write a Menu driven program to do the following operations:


1. New File
2. Display
3. Add in file
4. Exit
Write a function copy( ) which reads a file story.txt and copy all the alphabets
in alpha.txt, all the digits in digit.txt and other characters in other.txt.

#-----------------------Binary
File------------------------------------------------------------------------------------------------------------
Binary Files are not saved in human readable format when opened in text editor.
0,1
Binary Files can range from image files like JPEG or GIF, audio files like MP3 or binary document formats like
word or PDF.

binary file extenstion -----> .dat

JPEG - Joint Photographic Expert Group


GIF - Graphics Interchange Format
PDF - Portable Document Format

ASCII - American standard code for information interchange

Text File - Notepad -


Extension : .txt
Wordpad
Extension : . rtf (Rich Text Format)
MS-Word: .doc

a=5
print(type(a))

class :- It is a named group of properties and functions.


It is a blueprint of newly created object.

Ex: Car, Student, Teacher etc.

Object :- It is an instance of class which is capable of storing data of class type.


Ex: Swift, WagonR, Santro etc are objects of car class.

The data stored as collection(List or dictionary) or object of a class will also come in binary file, where the data
other than
string also converted to its byte equivalent ascii/unicode character before it is being saved.

Text file is be default.

Binary file modes are rb,wb,ab,rb+.

In Python, 'Binary files' can be created using pickle,JSON(Java Script Object Notation) or cpickle modules.

pickle is used for serializing or de-serializing python collections/object structures.

serialization refers to the process of converting collections/objects in memory to byte stream that can be stored
on disk or
sent over to network.
Later on, this stream can than be retreived and de-serialized back to python object.

pickle is specific to python module, thus cross language(even cross versions of pyhon).

Q. How to write data in binary file?

dump()
It is used to write the data(object,list,dictionary etc.) in binary file in the python laguage.

Syntax:
pickle.dump(<collection/object>,<file_object>)

write the pickled representation of collection/object to the open file object file.

Q. How to read data in binary file?

load()
Reads the pickle representation from collection/object(s) from the open file object file and return the
reconstituted hierarchy
specified therein. This is equal to unpickle.

<collection/object>= pickle.load(<file_object>)

#-------------------------------------------------------------------------------------------------------------------------------
#WAP to create a binary file 'student.dat'and then store a list containing [1,'Raj',75.5].
#------------------------------------------------------------------------------------------------------------------------------

import pickle
with open('student.dat','wb') as f:
pickle.dump([1,'Raj',75.5],f)

#----------------------------------------------------------------
OR

import pickle
f = open('student.dat','wb')
L = [1,'Raj',75.5]
pickle.dump(L,f)
f.close()

#-------------------------------------------------------------------------------------------------------------------------------------
-----------
#WAP to display the contents of a binary file 'student.dat'.
#-------------------------------------------------------------------------------------------------------------------------------------
-----------
import pickle
with open('student.dat','rb') as f:
print(pickle.load(f))

OR

import pickle
f=open('student.dat','rb')
L = pickle.load(f)
print(L)

#-------------------------------------------------------------------------------------------------------------------------------------
--------------
#WAP to create a binary file 'item.dat'and then store a directory containing {'Item No':1,'Item Name':'Pen'}.
#-------------------------------------------------------------------------------------------------------------------------------------
-------------

import pickle
with open('item.dat','wb') as f:
pickle.dump({'Item No':1,'Item Name':'Pen'},f)

#binary data (ASCII code convert to byte stream)

#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#WAP to display the contents of a binary file 'item.dat'.
#-------------------------------------------------------------------------------------------------------------------------------------
---------------

import pickle
with open('item.dat','rb') as f:
print(pickle.load(f)) #binary data (byte stream to convert to ASCII code)

#-------------------------------------------------------------------------------------------------------------------------------------
--------------
WAF to create a binary file 'student.dat' and then store rollno,name and marks of students till user wants to
store.
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
import pickle
def Create():
f = open('student.dat','wb')
L = [] # empty list L = list()
while True:
Rollno = int(input('Enter Roll No : ')) # int() - convert string value to integer value
Name = input('Enter Name : ')
Marks = float(input('Enter marks : '))# float() - convert string value to float value

L.append([Rollno,Name,Marks]) #nested list

ch = input('\nPress [n/N] to exit : ')


if ch in('n','N'):
break
pickle.dump(L,f) #write the data of list in binary file
f.close()

#-------------------------------------------------------------------------------------------------------------------------------------
------
#WAF to display the contents of binary file 'student.dat'
#-------------------------------------------------------------------------------------------------------------------------------------
-------

import pickle
def Display():
try:
f = open('student.dat','rb')
L = pickle.load(f)

print('\nRNO','NAME','MARKS',sep='\t')
for k in L:
print(k[0],k[1],k[2],sep='\t')
f.close()
except FileNotFoundError:
print('File not Found')

#-----------------------------------------------------------------------------
--------------------------------------------------------------
#WAF to display the information of a student which is stored in a binary file 'student.dat'
#whose roll no is entered by user, [Rollno, Name, Marks]
#display appropriate message if the record not exist

import pickle
def Search():
f = open('student.dat','rb')
L = pickle.load(f)

Rno = int(input('Enter Roll No to Search : '))

for k in L:
if Rno == k[0]:
print('Name :',k[1])
print('Marks : ',k[2])
break
else:
print('No such record exist.........')
f.close()

#--------------------------------------------------------------------------------
#WAF to display the information of the student(s) which is stored in a binary file 'student.dat'
#whose name is passed as argument,
#display appropriate message if the record not exist

import pickle
def Search_Name(Name):
f = open('student.dat','rb')
L = pickle.load(f)

found=0
for k in L:
if Name == k[1]:
print('Roll No :',k[0])
print('Marks : ',k[2])
found=1
if found==0:
print('No such record exist.........')
f.close()

#WAF to display the information of the student(s) which is stored in a binary file 'student.dat'
#whose marks are above 75 and display
#appropriate message if the record not exist

import pickle
def Search_above75():
f = open('student.dat','rb')
L = pickle.load(f)
found=0
for k in L:
if k[2]>75:
print(k[0],k[1],k[2],sep='\t')
found=1
if found==0:
print('No such record exist.........')
f.close()
#WAF to add more records in a binary file 'student.dat',which is already existed.

def Append():
f = open('student.dat','rb+') #read and write in file (modify)
data = pickle.load(f)

while True:
Rollno = int(input('Enter Roll No : '))
Name = input('Enter Name : ')
Marks = float(input('Enter marks : '))

data.append([Rollno,Name,Marks])
ch = input('Continue y/n : ')
if ch in('n','N'):
break

f.seek(0) #goto the beginning of file


pickle.dump(data,f)
f.close()

#WAF to modify the details of a student whose rollno is entered by user, from an existing binary
#file 'student.dat'
#-------------------------------------------------------------------------------------------------------------------------------------
------

import pickle
def Modify():
f = open('student.dat','rb+')
data = pickle.load(f)

Rno = int(input('Enter Roll No whose data you want to Modify : '))

for k in data:
if Rno == k[0]:
print('Name :',k[1])
print('Marks : ',k[2])

choice = input('Modify y/n : ')


if choice in ('y','Y'):
k[1] = input('Enter New Name : ')
k[2] = float(input('Enter New Marks : '))
break
else:
print('No such record exist.........')
f.seek(0)
pickle.dump(data,f)
f.close()

#-------------------------------------------------------------------------------------------------------------------------------------
-----
#WAF to remove the details of a student whose Rollno is specified by user. The binary file 'student.dat' is
already exist'
#-------------------------------------------------------------------------------------------------------------------------------------
--------

def Delete(): #Create,Display,Append,Search,Modify,Delete


L=[] # to store data of binary file
found=0
L1=[]
Rno = int(input('Enter Roll No to delete record : '))
with open('student.dat','rb') as f:
L = pickle.load(f)
for k in L:
if Rno == k[0]:
found = 1
print('Name :',k[1])
print('Marks : ',k[2])
print('Record deleted.........')
else:
L1.append(k) #temporary
if found==0:
print(Rno,'not found')
else:
with open('student.dat','wb') as f:
pickle.dump(L1,f)

#----------------------------------------------------------------------------------
while True:
ch = int(input('1. New Student 2. Display 3. Search 4. Modify 5. Add 6. Delete 7. Exit : '))
if ch == 1:
Create()
elif ch == 2:
Display()
elif ch == 3:
Search()
elif ch == 4:
Modify()
elif ch == 5:
Append()
elif ch==6:
Delete()
elif ch == 7:
print('Exit the Menu ..............')
break
else:
print('Invalid choice, Retry 1/2/3/4')

#-------------------------------------------------------------------------------
53214
35214
32514
32154
32145

23145
21345
21345

12345
12345

12345

def Bubble_Sort(L):
N = len(L)
for i in range(0,N-1,1): #Number of passes
for j in range(0,N-1-i,1): #adjacent elements
if L[j+1]<L[j]:
L[j],L[j+1] = L[j+1],L[j]

L = [5,3,4,1,2]
print(L)
Bubble_Sort(L)
print('after sort list is : ',L)

# -------------------------------------------------------------------------------
Sorting of Nested List on Second Element
# -------------------------------------------------------------------------------
def MySort(L):
N=len(L)
for I in range(N):
for J in range(N-I-1):
if L[J][1]>L[J+1][1]:
L[J],L[J+1]=L[J+1],L[J]

# -------------------------------------------------------------------------------
L=[[10,"AMIT",100],[2,"TINA",89],[7,"JANHWI",92],[5,"BABAN",65],[8,"MITA",76]]
print(L)
MySort(L)
print(L)

#-------------------------------------------------------------------------------------------------------------------------------------
----------------

import pickle
def Create():
with open('books.dat','wb') as f:
L = []
while True:
BNO = int(input('Book Number : '))
TITLE =input('Book Title : ')
AUTHOR = input('Book Author : ')
TYPE = input('Book Type : ')

L.append([BNO,TITLE,AUTHOR,TYPE])

choice = input('More [y/n] : ')


if choice in ('n','N'):
break
pickle.dump(L,f)
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
def Display(fname):
with open(fname,'rb') as f:
L = pickle.load(f)
print('\nBNO\tTITLE\t\t\t\tAUTHOR\t\t\t\tTYPE\n')
for k in L:
print(k[0],k[1],'\t\t',k[2],'\t',k[3],sep='\t')
#-------------------------------------------------------------------------------------------------------------------------------------
------------
def Add():
with open('books.dat','rb+') as f:
L = pickle.load(f)
while True:
BNO = int(input('Book Number : '))
TITLE =input('Book Title : ')
AUTHOR = input('Book Author : ')
TYPE = input('Book Type : ')

L.append([BNO,TITLE,AUTHOR,TYPE])

choice = input('More [y/n] : ')


if choice in ('n','N'):
break
f.seek(0) # go to the beginning of file
pickle.dump(L,f)
#-------------------------------------------------------------------------------------------------------------------------------------
-------
def Search_BNO():
with open('books.dat','rb') as f:
L = pickle.load(f)
BNO = int(input('Enter Book No to Search : '))
for k in L:
if k[0]==BNO:
print('Book Title: ',k[1])
print('Book Author: ',k[2])
print('Book Type: ',k[3])
break
else:
print('Book No',BNO,'not found')
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
def Search_AUTHOR():
with open('books.dat','rb') as f:
L = pickle.load(f)
found=0
AUTHOR = input('Enter Book Author to Search : ')
print('\nBNO\tTITLE\t\t\t\tAUTHOR\t\t\t\tTYPE\n')
for k in L:
if k[2]==AUTHOR:
print(k[0],k[1],'\t\t',k[2],'\t',k[3],sep='\t')
found=1
if found==0:
print('Book Author',AUTHOR,'not found')
#-------------------------------------------------------------------------------------------------------------------------------------
--------------
def Search_TITLE():
with open('books.dat','rb') as f:
L = pickle.load(f)
found=0
TITLE = input('Enter Book Title to Search : ')
print('\nBNO\tTITLE\t\t\t\tAUTHOR\t\t\t\tTYPE\n')
for k in L:
if k[1]==TITLE:
print(k[0],k[1],'\t\t',k[2],'\t',k[3],sep='\t')
found=1
if found==0:
print('Book Title',TITLE,'not found')
#-------------------------------------------------------------------------------------------------------------------------------------
--------
def Search_TYPE():
with open('books.dat','rb') as f:
L = pickle.load(f)
found=0
TYPE = input('Enter Book Type to Search : ')
print('\nBNO\tTITLE\t\t\t\tAUTHOR\t\t\t\tTYPE\n')
for k in L:
if k[3]==TYPE:
print(k[0],k[1],'\t\t',k[2],'\t',k[3],sep='\t')
found=1
if found==0:
print('Book Type',TYPE,'not found')
#-------------------------------------------------------------------------------------------------------------------------------------
-----------
def Count_TYPE():
with open('books.dat','rb') as f:
L = pickle.load(f)
L1=[]
for i in L:
if i[3] not in L1:
L1.append(i[3])

print('TYPE\t\tFREQUENCY\n')
for i in range(len(L1)):
count=0
for j in L:
if j[3]==L1[i]:
count +=1
print(L1[i],count,sep='\t\t')

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
#Write a function to arrange the binary file "books.dat" according to their type. File contains Book No,
Title,author and type.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------

def Sort_Author():
with open('books.dat','rb') as f:
L = pickle.load(f)

#Sorting Code - Bubble


for a in range(len(L)): #passes
for b in range(len(L)-a-1):
if L[b][2] > L[b+1][2]:
L[b][2],L[b+1][2]=L[b+1][2],L[b][2]

with open('books.dat','wb') as f:
pickle.dump(L,f)

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
#copy finction type books to binary file 'fiction.dat'
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
def Copy_Fiction():
with open('books.dat','rb') as f:
data = pickle.load(f)
L = []
for k in data:
if k[3]=='Fiction':
L.append(k)

with open('fiction.dat','wb') as f:
pickle.dump(L,f)

Add()
Display('books.dat')
Sort_Author()
Display('books.dat')
Copy_Fiction()
Display('fiction.dat')

Count_TYPE()
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
PRACTICAL LIST – 3
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
Binary File
Books organization System

Assuming "My Favorite Club" maintains the following data ot its books for their reader:

• BNO - Book Number


• TITLE - Book Title
• AUTHOR - Book Author
• TYPE - Book Type

Write a python code with the following options using user – defined functions:
1. To add new Book
2. To Search for a Book on the basis of Book No
3. To Search for a Book on the basis of Title
4. To Search for a Book on the basis of Author
5. To display books of particular type
6. To count number of books of each type
7. To arrange and display the details of books in ascending order of Title of the books
8. To modify type of a book (with matching BNO)
9. To view details / list of all the Books.
10. To Transfer the books of type “Fiction” to another file “Fiction.dat”.

Banking Accounts Management System

Assuming “Global Money bank” maintains the following data of its customers:
• ACNO – Account Number
• NAME – Customer Name
• MOBILE – Customer Mobile
• BALANCE – Customer Balance Amount in bank
• TRANS – Transaction Type [‘D’-Deposit, ‘W’-Withdrawal , ‘I’: Interest]
• TDATE – Transaction Date

Write a python code with the following options using user – defined functions:
1. To add new Customer
2. To Search for a customer on the basis of Account No.
3. To modify mobile number of customer (with matching account number)
4. To allow deposit money from a customer’s account by searching for a particular customer’s data matching
with an Accno and
updating (adding in the balance) the same and changing the TRDATE (and TRANS to ‘D’)
5. To allow withdraw money from a customer’s account by searching for a particular customer’s data matching
with an Accno and
updating (subtracting from the balance) of the same by subtracting the amount from Balance and updating
the TRDATE
(if and only if the customer has sufficient balance to allow withdraw) (and TRANS to ‘W’)
6. To view all the content of customers
#-------------------------------------------------------------------------------------------------------------------------------------
--------------
Following is the structure of each record in a data file named ”PRODUCT.DAT”.
"prod_code", "prod_desc", "stock"}
The values for prod_code and prod_desc are strings, and the value for stock is an integer.
Write a function in PYTHON to update the file with a new value of stock. The stock and the product_code,
whose stock is to be updated, are to be input during the execution of the function.

import pickle
def Add():
with open('PRODUCT.DAT','wb') as f:
D= {}
while True:
prod_code= input('Product Code : ')
prod_desc =input('Description : ')
stock = int(input('Stock : '))

data = (prod_desc,stock)
D[prod_code]=data
choice = input('More [y/n] : ')
if choice in ('n','N'):
break
pickle.dump(D,f)
#-------------------------------------------------------------------------------------------------------------------------------------
-------

import pickle
def Display():
with open('PRODUCT.DAT','rb') as f:
L = pickle.load(f)

for k in L:
print(k[0],end='')
z = L[k]
for i in z:
print(i,end='')
print()
#Add()
Display()
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
def Modify():
f = open('product.dat','rb+')
data = pickle.load(f)

PID = input('Enter Product ID whose data you want to Modify : ')


for k in data:
if PID == k[0]:
print('Description :',k[1])
print('Stock : ',k[2])

choice = input('Modify y/n : ')


if choice in ('y','Y'):
k[2] = int(input('Enter New Stock : '))
break
else:
print('No such record exist.........')
f.seek(0)
pickle.dump(data,f)
f.close()

Display()
Modify()
Display()

#------------No of records in file -------------------------------------------

import pickle
def Display():
with open('PRODUCT.DAT','rb') as f:
L = pickle.load(f)
print(len(L))

Display()
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#-------------------------------------------------------------------------------------------------------------------------------------
---------------

CSV - Comma Separated Values

These are delimited files that sore tabular data (data stores in rows and columns as we see in spreadsheets or
databases)
where comma delimits every value.

It is a type of plain text file that uses specific structuring to arrange tabular data.
because it is a plain text file, it can contain only actual text data - in other words printable ASCII or unicode
characters.

- can be used to databases and spreadsheet (MS Excel, open office-calc,google sheets etc.)

The structure of a CSV file is given by its name. Normally, CSV file use a comma to separate each specific data
value.

1,"raj",76.5 <-------------- record

There are different ways to handle this situation:


* Delimiter- comma is default delimiter, which can be changed to any other such as '\t' or any other character(-).
* Quotes - we can enclose the data in quotes, if it includes the delimiter character.

print('hi')

print("HI")

print("It's me") csv - > excel import data--------------> tabular

print('It"s me')

These are popular because of these reasons:


1. Easier to create
2. Preferred export and import format for databases and spreadsheets(MS Excel , Google sheet, open office
calc).
to_csv() read_csv()
3. Capable of storing large amounts of data.
#-------------------------------------------------------------------------------------------------------------------------------------
---------------

text file : write(), writelines() read(), readline(),readlines() no


module

binary file: dump() load() pickle


module

csv file writer(), writerow(), writerows() reader() csv


module
#-------------------------------------------------------------------------------------------------------------------------------------
---------------

Q. Which module is required for CSV file operations?

import csv
#How many ways we can import module?

import math
print(math.sqrt(81))

from math import sqrt


print(sqrt(81))

from math import *


print(sqrt(81))
print(pow(3,4))

Q. How to open csv file?

file_object = open(filename.csv,mode) mode - r,w,a,r+

with open(filename.csv,mode) as file_object


No need to close file, as it will be closed automatically.

Q. How to write data in CSV file?

user data is written on a csv.writer object which converts the user data into delimited form and writes it on to the
csv file.

csv.writer() - returnd a write object which writes data into CSV file.

Syntax:
writeobject = csv.writer(CSVfileobject,delimiter=',')

<writer_object>.writerow() - writes a record/row of data onto the writer object.

1,Raj,75.5

<writer_object>.writerows() - writes multiple rows/records of data onto the writer object.

Record -
It is a collection of related values - 1,"Raj",87.5

csv file should be opened with newline argument to supress EOL translation.

Q. WAF to create a CSV file score.csv and then store 3 records in it.

import csv
def Create():
with open("score.csv","w",newline='') as f:
cv = csv.writer(f,delimiter=',') # cv is object
cv.writerow(['Team','Score'])
cv.writerow(['A',98])
cv.writerow(['B',91])
cv.writerow(['C',85])

#Q. How to read the contents of CSV file?


csv.reader() - returns a reader object which loads data from CSV file into an iterable after parsing delimited
data.
It will work only when CSV file is opened as a text file in "r" mode.
#Q. WAF to display the contents of a CSV file score.csv

def Display():
with open("score.csv","r") as f:
data = csv.reader(f,delimiter=',')
for k in data:
print(k[0],k[1],sep='\t')

Q. WAF to create a csv file student.csv for writing Roll no, Name and marks till user wants to continue.

import csv
def Create():
with open('student.csv','w',newline='') as f:
cv = csv.writer(f,delimiter=',')

while True:
Rollno = int(input('Enter Roll No : '))
Name = input('Enter Name : ')
Marks = float(input('Enter Marks : '))

cv.writerow([Rollno,Name,Marks])

choice = input('More Y/N ? ')


if choice in ('n','N'):
break

#-------------------------------------------------------------------------------------------------------------------------------------
------------
#Q. Write a function to display the details of a csv file student.csv.

def Display():
try:
with open('student.csv','r') as f:
data = csv.reader(f,delimiter=',')
print('Roll NO Name Marks ')
for k in data:
print(k[0],k[1],k[2],sep='\t')
except FileNotFoundError:
print('File not found')

#-------------------------------------------------------------------------------------------------------------------------------------
------------

def Append():
with open('student.csv','a',newline='') as f:
cv = csv.writer(f,delimiter=',')

while True:
Rollno = int(input('Enter Roll No : '))
Name = input('Enter Name : ')
Marks = float(input('Enter Marks : '))

cv.writerow([Rollno,Name,Marks])

choice = input('More Y/N ? ')


if choice in ('n','N'):
break

#-------------------------------------------------------------------------------------------------------------------------------------
-----
#WAF Search() to display the detail of the student whose Roll No is entered by user.
def Search():
try:
with open('student.csv','r') as f:
data = csv.reader(f,delimiter=',')
Rno = int(input('Enter Roll No : '))

for k in data:
if int(k[0]) == Rno:
print('Name : ',k[1])
print('Marks : ',k[2])
break
else:
print('No Such Record Exist.............')
except FileNotFoundError:
print('File not found')

#-------------------------------------------------------------------------------------------------------------------------------------
------------
while True:
choice = int(input('1. Create File 2. Append Data 3. Display 4. Search 5. Exit : '))
if choice==1:
Create()
elif choice==2:
Append()
elif choice==3:
Display()
elif choice==4:
Search()
elif choice==5:
print('Exit the program.......................')
break
else:
print('Invalid Choice, Retry 1/2/3/4/5')

#-------------------------------------------------------------------------------------------------------------------------------------
----------------

Q 1. Write a Python code with independent user defined functions to perform the following operations on a
CSV file "MEMBER.CSV":
(a) To add details of new members (Mno, Name, Fee, Type) in the csv file with the content of the user.
(b) To display the details of all the members from the csv file.
(c) To calculate and display total fee from the csv file.
(d) To search for a member matching with Mno entered by user and display the details of the member from
the csv file.
(e) To display details of a particular type of members from the csv file.

Note:
-There should be appropriate exception handling for checking existence of the file while reading the content
from the file.
-There should be a menu driven option to call the above user defined functions.

Q. Write a Python code with independent user defined functions to perform the following operations on a CSV
file "STOCK.CSV":
(a) To add details of new items (Ino, item, Price, Qty) in the csv file with the content of the user.
(b) To display the details of all the items along with stock value of each item (Price * Qty) from the csv file.
(c) To display all the items, whose qty is less than 10 in the stock.
(d) To search for an item matching with Ino entered by user and display the details of the member from the
csv file.

Note:
-There should be appropriate exception handling for checking existence of the file while reading the content
from the file.
-There should be a menu driven option to call the above user defined functions.
#-------------------------------------------------------------------------------------------------------------------------------------
------------

1. _______________ for,at is a text format accessible to all applications across deveral platforms.
2._______________ method is used for random access of data in a CSV file.
3. ___________ method of pickle module is used to write an object into binary file.
4. Which statement is used to import csv module into your program.
5. load() method of _______ module is used to read data from binary file.
6. __ is a string method that joins all values of each row with comma separator in CSV file.
7. To force python to write the contents of file buffer on to storage file, ______ method may be used.

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Error
It is something which prevents a program from compiling and running correctly.

Debugging
Removing errors
Type
Compile time errors

Syntax errors : These are the errors which occurs on violation of grammatical rules of a programming
language.
Ex: print 'hi'

Semantics errors : These errors occurs due to meaningless statements.


Ex: x+y = z

Run time errors : These are the errors which occcurs at the time of program execution.
Exceptions

1. FileNotFoundError
2. NameError
3. TypeError
4. ValueError
5. ZeroDivisionError
6. IOError

#-------------------------------------------------------------------------------------------------------------------------------------
------------

logical errors : These are the errors which occurs due to wrong analysis. These are not detected by interpreter.
So programmer has to detect and correct these mistakes.
#-------------------------------------------------------------------------------------------------------------------------------------
------------

Display string s with each letter in new line

s = 'RAJESH'
print(s)
try:
s[2] = 'K'
print(s)
except:
print('String is immutable')

#-------------------------------------------------------------------------------------------------------------------------------------
------------

A=10;B=20
C=30
print(A,B,C,sep="&",end=' ')
B,C=C,B
while A<=B:
if A<C:
C-=2
elif A==B:
C+=5
print(A,B,C,end=' ')
A+=10

#-------------------------------------------------------------------------------------------------------------------------------------
------------

j=5
while j<15:
if j%5!=0:
print (j,end='#')
else:
print('well done',end='\t')
j = j +2
print(j)

#-------------------------------------------------------------------------------------------------------------------------------------
------------

for k in range(5):
print(k*2)
#-------------------------------------------------------------------------------------------------------------------------------------
------------

Find the output


def Find(D,P=2):
for k in D:
if D[k]%10==0:
D[k] += 5
print(3*"#",D[k],end='$')
else:
D[k] -= P

d = {'A':30,'B':25,'C':45}
Find(d)
print(d,end='@')
Find(d,7)
print(d,end='^')

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Find the output

def Add(*D):
sum = 0
print('Data = ',D,end='#')
for i in D:
sum += i
return (sum)

print(Add(9,1,4,51),end='$')
print(Add(7,3),end='@')

#-------------------------------------------------------------------------------------------------------------------------------------
------------
Data = (9, 1, 4, 51)#65$Data = (7, 3)#10@
#-------------------------------------------------------------------------------
In csv files, what does the first row in the file typically contain?
a. The source of the data
b. Notes about the table data
c. The column names of the data
d. The author of the table data
#-------------------------------------------------------------------------------------------------------------------------------------
------------

Which of the following is not an attribute related to a file object?


a) closed
b) mode
c) name
d) rename

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Which of the following statements correctly explain the function of tell() method?
a) Tells the current position within the file.
b) Indicates that the next read or write will occur at that many bytes from the
beginning of the file.
c) Move the current file position to a different location.
d) It changes the file position only if allowed to do so else return an error.

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Which of the following statements is not correct regarding the file access modes?
a) „r+‟ opens a file for both reading and writing. File object points to its beginning.
b) „w‟ opens a file for both writing and reading. Overwrites the existing file if it exists and creates a new
one if it does not exist.
c) „wb‟ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates a
new one if it does not exist.
d) „a‟ opens a file for appending. The file pointer is at the end of the file if the file exists.

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Write the name of the functions used to read and write in a CSV file?

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Write the Full form of CSV.

#-------------------------------------------------------------------------------------------------------------------------------------
------------

Find and write the output of the following Python code:

def PRINT(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m = m + str[i].lower()
elif str[i].islower():
m = m + str[i].upper()
else:
if i%2==0:
m = m + str[i-1]
else:
m = m +"#"
print(m)

PRINT('[email protected]')

#-------------------------------------------------------------------------------------------------------------------------------------
------------

with open('Writer.txt','w') as f:
f.write('Covid LockDown')

The contents of the Writer.txt file is as follows:


Python is Now in CS Course
Covid LockDown
Find the output of the following code:

def display():
y=0
f=open("Writer.txt","r")
r=f.read()
t=r.split()
for x in t:
if x.islower():
print(x,end='$')
else:
y=y+1
print(y,end='#')
f.close()

display()

#-------------------------------------------------------------------------------------------------------------------------------------
------------
1#2#
#-----------------------------------------------------------------------------------------------------------------------------
Find the output of the following code segment:
def calculate(a,b=3,c=5):
a=a+b-c
b=b+c-a
c=c+a-b
print(a,b,c,end='#')

calculate(10,15,30)
calculate(10)

#-------------------------------------------------------------------------------------------------------------------------------------
------------
-5 50 -25#8 0 13#
#------------------------------------------------------

Write a function CountAlphabet() in Python, which should read each character of a text
file STORY.TXT, should count and display the occurrence of alphabets K and N (including
small cases k and n too).
Example:
If the file content is as follows:
Updated information:
Knowledgeable persons knows how to handle the situation
The CountAlphabet() function should display the output as:
N or n:7
K or k :2

#-------------------------------------------------------------------------------------------------------------------------------------
------------

A binary file “STUDENT.DAT” has a record of structure [admission_number, Name,


Percentage]. Write a functions
i. To input data for STUDENT.DAT and write the data into the file. (2 marks)
ii. To read contents of the file “STUDENT.DAT” and transfer the record to another file
“Distinct.dat” for those students whose percentage is above 75. (4 Marks)

#-------------------------------------------------------------------------------------------------------------------------------------
------------

A text file mydata.txt is stored in your device with 10 lines of texts stored. You want
to add 3 more lines of texts without removing the already existing texts from the file.
Write a code statement to open the file.

def Manip(k,L):
k += 2*L
L -= 10
print('k:',k,'L:',L,end='&')
Manip(L=100,k=50)
Manip(25,50)

#----------------------------------------------------
k: 250 L: 90&k: 125 L: 40&
# ------------------------------------
Find the output of the following

def Exec(a=50,b = 25):


a += b
b += a
print('a->',a,'b->',b,end=' $ ')
Exec()
P=10;Q=100
Exec(b=P,a=Q)
Exec(b=P)

#-------------------------------------------------------------------------------------------------

a = 900
def Calculate():
global a
b = 10
a += b
print('=>',a,a//b,end='&')

print(a,end='$')
Calculate()
print(a)
#-------------------------------------------------------------------------------------------------
900$=> 910 91&910
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
#-------------------------------------------------------------------------------------------------------------------------------------
-----------------
Data Structres in Python

Data struture
It is a way of storing, organizing and retrieving data in a computer so that it can be used most
efficiently.
It can store data of similar or different data types which can be processed as a single unit.

Lists are dynamic in nature i.e. they can grow/increase and shrink/decrease in size/number of items as
and when required.
They are heterogeneous.

String,List,Tuple -----> Sequence datatype


Dictionary --> mapping

Nested List : A list that has one or more lists as its elements.

For Ex:
L = [10,23,56,[78,9]]

0 1 2 [3][0],[3][1]

L.pop() - remove the last element, if parameter is passed then that particular index element will be removed
return the deleted value
L = [3,1,5,2]

L.pop(2)

L.remove(value) - parameter is value

L.remove(78)

del L[index]

List - search -

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
linear Search binary Search
#-------------------------------------------------------------------------------------------------------------------------------------
----------------

1. No pre-condition 1. List must be sorted ie. ascending or descending order

2. It will compare with each element of 2. It will find the middle location and then compare if
found then ok
list, so max number of comaprisons otherwise check in LHS or RHS, so max comparisons
are equal to
i.e app. list size app. half of list size
#-------------------------------------------------------------------------------------------------------------------------------------
----------------

L=[5,2,8,3,6,1,4]

data = int(input('Enter Search value : '))

if data in L:
print(data,'found')
else:
print(data,'not found')

#Q. Replace each odd element with their square and even elements with their half.

for k in range(len(L)):
if L[k]%2==1:
L[k] = L[k]**2
else:
L[k] = L[k]//2
print(L)

#-------------------------------------------------------------------------------------------------------------------------------------
----------------

L=[5,2,8,3,6,1,4]

print(L)
L.sort()
print(L)

data = int(input('Enter Search value : '))

found=0
beg=0
last = len(L)-1

while beg<=last:
mid = (beg+last)//2
if L[mid]==data:
print(data,'found at ',mid,'location')
found=1
break
elif data>L[mid]:
beg = mid + 1
else:
last=mid-1
if found==0:
print(data,'not found..............')

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
sorting - bubble, insertion, selection

bubble sort
It the technique in which adjacent elements are compared and if not in order then interchange.

Ascending

L = [5,4,3,2,1]

5,4,3,2,1 First Pass


4,5,3,2,1
4,3,5,2,1
4,3,2,5,1
4,3,2,1,5

3,4,2,1,5 Second pass


3,2,4,1,5
3,2,1,4,5

2,3,1,4,5 Third pass


2,1,3,4,5

1,2,3,4,5 Fourth Pass

def Bubble_Sort(L):
N = len(L)
for i in range(0,N-1,1): #passes N - 5 i - 0,1,2,3
for j in range(0,(N-1-i),1):
if L[j+1]<L[j]:
L[j],L[j+1] = L[j+1],L[j]

L = [5,2,7,3,9,4]
print(L)
Bubble_Sort(L)
print('After sort : ',L)

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
Selection Sort -- Ascending
In this technique find the location of smallest element and then interchange with 0 index element, and the
find the smallest in
the remaining array and then interchange with 1 index and this process will go on till the last.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
Ascending

4,1,7,2,3,6,5

1,4,7,2,3,6,5

1,2,7,4,3,6,5

1,2,3,4,7,6,5

1,2,3,4,5,6,7

def Selection_Sort(L):
N = len(L)
for j in range(0,N,1):
small = L[j]
pos = j
for i in range(j+1,N,1):
if L[i]<small:
small = L[i]
pos = i
L[j],L[pos] = L[pos],L[j]

L = [5,2,7,3,9,4]
print(L)
Selection_Sort(L)
print('After sort : ',L)

#-------------------------------------------------------------------------------------------------------------------------------------
----------------
Insertion Sort
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
4,1,7,2,3,6,5
1,4,7,2,3,6,5

1,4,7,2,3,6,5
1,2,4,7,3,6,5
1,2,3,4,7,6,5
1,2,3,4,6,7,5
1,2,3,4,5,6,7

def Insertion_Sort(nlist):
for index in range(1,len(nlist)):

currentvalue = nlist[index]
position = index

while position>0 and nlist[position-1]>currentvalue:


nlist[position]=nlist[position-1]
position = position-1

nlist[position]=currentvalue

#WAP to find the frequency of each integer in a list L

L = [1,2,3,2,5,4,1,2,3]

L1=[] # store unique numbers


for k in L:
if k not in L1:
L1.append(k)

print('Element','Frequency',sep='\t')
for k in L1: #unique elements
count=0
for j in L:
if k==j:
count+=1
print(k,count,sep='\t')

#WAF which takes a list as parameter and then shift its elemements to their Left.
01234
12345

23451

def LeftShift(L):
Temp = L[0]
for k in range(1,len(L),1):
L[k-1]=L[k]
L[-1]=Temp

L = [1,2,3,4,5]
print('List is : ',L)

LeftShift(L)

print('After Left shift, List is : ',L)

#-------------------------------------------------------------------------------------------------------------------------------------
---
Right Shift
Interchange First half side - Second Half
Interchange Adjacent elements interchange
#-------------------------------------------------------------------------------------------------------------------------------------
---

Stack Queue
front
6 8 9 2 1<----------------rear
8
4
7
9

Stack
It is a linear/sequence structure in which insertion and deletion can take place only at one end i.e. Stack's top.

It is called LIFO (Last in, first out) data structure.

Element inserted last would be the first to be deleted.

Ex. a pile of books, a stack of coins etc.

Push - is used to store element in stack.


Pop - is used to remove element from stack.

Queue
It is a linear/sequence structure in which insertion is done from rear end and deletion is done from front end.

It is called FIFO (First in, first out) data structure.

Element inserted first would be the deleted first.

Ex: Bank ATM, Fee counter, Shopping center etc.


Stack = []
while True:
choice = int(input('1. Push 2. Pop 3. Display 4. Exit : '))
if choice == 1:
Value = input('Enter Element to push in stack : ')
Stack.append(Value)
elif choice==2:
if len(Stack)!=0:
print('Deleting value is : ',Stack.pop())
else:
print('Stack underlow...........')
elif choice == 3:
if len(Stack)!=0:
print('\nStack is : ')
for k in range(len(Stack)-1,-1,-1):
print(Stack[k])
else:
print('Stack underlow...........')
elif choice == 4:
print('Exit the menu...........')
break
else:
print('Invalid Choice, Retry 1/2/3/4')

#-------------------------------------------------------------------------------------------------------------------------------------
-----------

Queue = []
while True:
choice = int(input('1. Insert 2. Remove 3. Display 4. Exit : '))
if choice == 1:
Value = input('Enter Element to push in stack : ')
Queue.append(Value)
elif choice==2:
if len(Queue)!=0:
print('Deleting value is : ',Queue.pop(0))
else:
print('Queue underlow...........')
elif choice == 3:
if len(Queue)!=0:
print('\nQueue is :\t ')
for k in range(0,len(Queue),1):
print(Queue[k],end='\t')
else:
print('Queue underlow...........')
elif choice == 4:
print('Exit the menu...........')
break
else:
print('Invalid Choice, Retry 1/2/3/4')

#--------------------------------------------------------------------------------------------------------------------------------

1. What will be the output of the following Python code:

a = [10,23,56,[78,10]]
b = list(a)
a[3][0] += 17
print(b)

#-------------------------------------------------------------------------------------------------------------------------------------
----
[10, 23, 56, [95, 10]]
#
-------------------------------------------------------------------------------------------------------------------------------
--------
2. Stack is a data structure that follows order
a. FIFO
b. LIFO
c. LILO
d. FILO

3. Queue is a data structure that follows order


a. FIFO
b. LIFO
c. LILO
d. FILO

4. What will be the output of the following Python code :


mylist =[‘java’,’c++’,’python’,’vb’,’vc++’,’php’,’cobol’]
print(mylist.pop())
mylist.append(‘c#’)
print(len(mylist))
mylist.insert(3,’basic’)
print(mylist)

5. Identify the error in following code:


(i) List1 = [10,20,30,40]
List1[4]=100
(ii) Name=”Michael Jackson”
Name[2]=”k”

6. Write down the status of Stack after each operation:


Stack =[10,20,30,40] where TOP item is 40
(i) Push 70
(ii) Push 100
(iii) Pop an item from Stack
(iv) Peek the Stack

7. Write down the status of Queue after each operation:


Queue=[10,20,30,40] where FRONT item is 10
(i) Insert 70
(ii) Remove item from Queue
(iii) Item at the front

8. Identify the Data Structure (Stack/Queue) used for following operations in computer?
(i) Function calling
(ii) Printer spooling
(iii) Undo operation
(iv) Solving expression
(v) Keyboard buffering

Ans: (i) Stack (ii) Queue (iii) Stack (iv) Stack (v) Queue

9. Given the list:


MYLIST = [5,11,17,19,25,29,30,30,32,46,90]

Write down the Python statements for the following requirement:


(i) To find the number of items in MYLIST
(ii) To find the frequency of item 30 in MYLIST i.e. how many times 30 is in MYLIST

10. Write the function sumAlternate(MYLIST) as argument and calculate the sum of all alternate elements of
MYLIST and print it

For e.g. if the elements are


5 11 17 19 25 29 30 32 56 90

Output should be :
Total = 133

#-------------------------------------------------------------------------------------------------------------------------------------

Interface Python with MySQL


Database: It is a collection of logically related information about a specific topic. Ex: bank, student etc.
Create database Test;
Use test; # test is my current database now

Python DB-API -
It is a widely used module that provides a database application programming interface.
Ex: MySQL, Oracle, Sybase, Ingres etc.

CLIENT - SERVER ARCHITECTURE

Front-end - It is the place where user provides queries or requests which has to be processed in back-end.
Ex: Visual basic, Python, Power Builder etc.

BROWSER - CHROME - WEBSITE ----------- IRCTC - DESTINATION - MUMBAI DATE - 18/2/2021

Back-end- It is the place where data is stored and processed and then result will be provided to front-end.
Ex: MySQL, Oracle, Sybase etc.

Why Python ?
1. Flexibility -
2. Portablity -
3. Plateform Independent
4. Supports Relational Database Systems.
5. Python database APIs are compatible with various databases.

Steps for creating database connectivity:

1. Importing the package(API module) for database programming

import mysql.connector
or
import mysql.connector as sql #sql is an alternative name

2. Open a connection to database

<conection object> =mysql.connector.connect(host=<host-name>,user = <user_name>,passwd=<pass


word>[,database = <database>])
host = 'localhost'
user = "root"
passwd = "" #empty if no password is to open mysql

optional - database if not already existed

if <conection object>.is_connected():
print('Successfully connected to MySQL database')
if <conection object>.is_connected()==False:
print('Error in connecting to MySQL database')

Example:

con = sql.connect(host='localhost',user ='root',passwd='',database = 'school')


OR
con = mysql.connector.connect(host='localhost',user ='root',passwd='',database = 'school')

3. create a cursor instance.

<cursor object > = <conection object>.cursor()

Example:
mycursor = con.cursor()

4. Execute a query.

<cursor object >.execute('command')

Example:

mycursor.execute('use school')

5. Extract data from resultset.

1. fetchone() - It fetches the next row of a query.


2. fetchall() - It fetches all the rows of a query.
3. fetchmany(<n>) - It fetches n rows of a query.
4. rowcount - returns the number of rows that are affected by execute() method.

6. Closing the connection/clean up the environment.


<cursor object >.close()

#-------------------------------------------------------------------------------------------------------------------------------------
------------------

WAF to display all the databases of your System.

def Display_Databases():
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='')
mycursor = mydb.cursor()
mycursor.execute('SHOW DATABASES')
for k in mycursor:
print(k)
mydb.close()

Display_Databases()

#-------------------------------------------------------------------------------------------------------------------------------------
------------------

WAF to create a database AARUSHI

def Create_Database():
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='')
mycursor = mydb.cursor()
mycursor.execute('create database AARUSHI')
print('Database has created............')
mydb.close()

Create_Database()

#--------------------------------------------------------------------------------------------------
#Create student table in AARUSHI database
#--------------------------------------------------------------------------------------------------

import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='',database='AARUSHI')
mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE STUDENT (ROLLNO INT(3) PRIMARY KEY, \


NAME VARCHAR(20), MARKS FLOAT(5,1))")
print('Table created..........')
mydb.close()

#-------------------------------------------------------------------------------------------------------------------------------------
--------------
#Insert a record in student table

MySQL categories of commands are:


1. DDL - CREATE, ALTER, DROP
2. DML - INSERT, UPDATE, DELETE
3. DCL - DATA CONTROL LANGUAGE ----> GRANT, REVOKE
4. TCL - TRANSACTION CONTROL LANGUAGE ----> COMMIT, ROLLBACK, SAVEPOINT
#-------------------------------------------------------------------------------------------------------------------------------------
------------
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='',database='AARUSHI')
mycursor = mydb.cursor()

mycursor.execute("insert into student values(1,'PRIYA',99.5)")


mycursor.execute("insert into student values(2,'Rajeev',98.5)")
mycursor.execute("insert into student values(3,'Rajesh',97.5)")

mydb.commit() #to save the changes done on the database

print('Records has inserted')


mydb.close()

#--------------------------------------------------------------------------------------------------

1. commit - to save the changes


2. rollback - to revert the changes made by current transaction.
3. savepoint - Book mark/tag
3. autocommit - It is used to make to autocommit on or off. By default ON

#--------------------------------------------------------------------------------------------------
WAP to store records in student table till user wants to store.

import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='',database='aarushi')
mycursor = mydb.cursor()
while True:
Rollno = int(input('Enter Roll No : '))
Name = input('Enter Name : ')
Marks = float(input('Enter Marks : '))

query = "insert into student values ({},'{}',{})".format(Rollno,Name,Marks)


mycursor.execute(query)

mydb.commit() #to save the changes done in the database


print('Record saved successfully')

choice = input('Do you want to continue Y/N ? ')


if choice in 'nN':
break
mydb.close()

#-------------------------------------------------------------------------------------------------------------------------------------
----------
Resultset
A logical set of records which are fetched from database based on query and made available to the application.
Example : SELECT

#-------------------------------------------------------------------------------------------------------------------------------------
--------------
# Display detail of all students from student table.
#-------------------------------------------------------------------------------------------------------------------------------------
--------

def Display():
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='',database='aarushi')
mycursor = mydb.cursor()
mycursor.execute('select * from student')
data = mycursor.fetchall() #to take data from cursor and then store in object

print('\n************************* Table : Student******************************\n')

for k in data:
print(k[0],k[1],k[2],sep='\t') # k[0] - Rollno k[1] - Name k[2] - Marks
mydb.close()

#--------------------------------------------------------------------------------------------------
#To remove the data from table student.
#--------------------------------------------------------------------------------------------------

import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='',database='aarushi')
mycursor = mydb.cursor()

mycursor.execute('delete from student where rollno = 5')


mydb.commit()
print(mycursor.rowcount,'record(s) has deleted......')
mydb.close()

Display()

#
-------------------------------------------------------------------------------------------------------------------------------
-------------------
Delete the details of the student whose Rollno is entered by user.
#
-------------------------------------------------------------------------------------------------------------------------------
-------------------
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user = 'root',passwd='',database='aarushi')
mycursor = mydb.cursor()
Rollno = int(input('Enter Roll No whose record has to delete : '))

mycursor.execute("delete from student where rollno = {}".format(Rollno))

mydb.commit()
print(mycursor.rowcount,'record(s) has deleted......')
mydb.close()

Display()

#-------------------------------------------------------------------------------------------------------------------------------------
--------------
# Increase the marks by specified marks whose roll no is entered by user.
#-------------------------------------------------------------------------------------------------------------------------------------
--------------

import mysql.connector as s #s is an alternative name


mydb = s.connect(host='localhost',user = 'root',passwd='',database='aarushi')
mycursor = mydb.cursor()

Rollno = int(input('Enter Roll No : '))


Marks = float(input('Enter Marks : '))

mycursor.execute("update student set marks = marks + {} where rollno = {}".format(Marks,Rollno))


mydb.commit()
print(mycursor.rowcount,'record(s) has updated......')
mydb.close()

Display()

#-------------------------------------------------------------------------------------------------------------------------------------
-------------
1. Explain how will you extract data from a resultsheet using fetch()?

2. Explain what the following query will do?


import mysql.connector
db = mysql.connector.connect(……)
cursor = db.cursor()
db.execute(“Select * from staff where person_id in {}”, format((1,3,4)))
db.commit()
db.close()
3. Which package must be imported in Python to create a database connectivity application?

4. What is Resultset?

5. What is the name of module used for connectivity?

6. Specify the name of parameters of connect() method?

#--------------------------------------------------------------------------------------------------
Topic- Interface Python with MySQL

#1. Design a Python application that fetches all the records from Pet table of Menagerie database.

import mysql.connector as s
db = s.connect(host = 'localhost',user='root',passwd='')
c = db.cursor()
c.execute('create database Menagerie')
c.execute('use Menagerie')
c.execute('create table pet(code int,name char(20))')
c.execute("insert into pet values(1,'Cat')")
db.commit()
c.execute('select * from pet')
for k in c:
print(k[0],k[1],sep='\t')
db.close()

#2. Design a Python application that fetches only those records from Event table of Menagerie database
where type is Kennel.

import mysql.connector as s
db = s.connect(host = 'localhost',user='root',passwd='')
c = db.cursor()
#c.execute('create database Menagerie')
c.execute('use Menagerie')
c.execute('create table event(Ecode int,Ename char(20),type char(30))')
c.execute("insert into event values(1,'ABC','XYZ')")
c.execute("insert into event values(2,'DEF','Kennel')")
c.execute("insert into event values(3,'UYT','ZXY')")
c.execute("insert into event values(4,'PWY','Kennel')")
db.commit()
c.execute("select * from event where type = 'Kennel'")
data = c.fetchall()
for k in data:
print(k[0],k[1],k[2],sep='\t')
db.close()
empno. ename job mgr hiredate sal comm deptno
8369 Smith Clerk 8902 18/12/1990 800 NULL 20
8499 Anya salesman 8698 20/2/1991 1600 300 30
8521 Seth salesman 8698 22/2/1991 1250 500 30
8566 Mahadevan Manager 8839 4/2/91 2985 NULL 20
8654 Mominsalesman 8698 28/9/1991 1250 1400 30
8698 Bina Manager 8839 5/1/91 2850 NULL 30
8882 Shivansh Manager 8839 9/6/91 2450 NULL 10
8888 Scott Analyst 8566 9/12/92 3000 NULL 20
8839 Amir President NULL 18/11/1991 5000 NULL 10
8844 Kuldeep salesman 8698 9/8/1991 1500 0 30
8886 Anoop Clerk 8888 12/1/93 1100 NULL 20
8900 Jatin Clerk 8698 3/12/91 950 NULL 30
8902 Fakir Analyst 8566 3/12/91 3000 NULL 20
8934 Mita Clerk 8882 23/01/1992 1300 NULL 10

import mysql.connector as s
db = s.connect(host = 'localhost',user='root',passwd='')
c = db.cursor()
c.execute('create database Menagerie')
c.execute('use Menagerie')
c.execute('create table dept(deptno int(4) primary key,dname char(20),loc char(20))')
c.execute('create table emp(empno int(4) primary key,ename char(20),job char(20),mgr int(4),hiredate date,sal
int,comm int,deptno int(4), foreign key(deptno) references dept(deptno))')
c.execute("insert into emp values(8369,'Smith','Clerk',8902,'1990-12-18',800,NULL,20)")

c.execute("insert into dept values(10,'Sales','Delhi')")


c.execute("insert into dept values(20,'HR','Mumbai')")
db.commit()
c.execute("select * from emp")
data = c.fetchall()
for k in data:
print(k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7],sep='\t')
db.close()

3. Design a Python application to obtain search criteria from user and then fetch records based on that from
emp table.

try:
import mysql.connector as s
db = s.connect(host = 'localhost',user='root',passwd='')
c = db.cursor()
c.execute('use Menagerie')
empno=int(input('Enter Employee No: '))

c.execute("select * from emp where empno = {}".format(empno))


data = c.fetchall()
if len(data)==0:
print('No Such employee exist')
else:
for k in data:
print(k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7],sep='\t')
db.close()
except:
print('Error in connectivity')

X,Y=54,67
while Y<X
if Y%5==0:
print(X+Y)
elif Y%2==0:
print(X-Y)
else:
print(X*Y)
Y+=4

N = int(input('Enter a number : '))


sum = 0
while N>0:
r = N%10
sum = sum + r**4
N = N//10
print(sum)

1. a) Which of the following can be used as valid variable identifier(s) in Python?


(i) 6thproduct (ii) Total (iii) valuer# (iv) Int 2
b) Identify and write the name of the module to which the following functions belong: 1
(i) randint() (ii) findall()
c) Observe the following Python code very carefully and rewrite it after removing all syntactical errors with
each correction underlined. 2
DEF examain():
x = int(input("Enter a number:") if (abs(x)= x):
print"You entered a positive number" else:
x=*-1
print "Number made positive:" x) execmain()

d) Write the output of the following program code : 2


L1 = [100,900,300,400]
START = 1 SUM = 0
for C in range(START,3): SUM = SUM + L1[C]
print(C, ":", SUM)
SUM = SUM + L1[0]*10
print(“the final value is “,SUM)
e) Write a user-defined function to generate odd numbers between a and b (including b). Note: a and b are
received as an argument by the function. 3
f) List one similarity and one difference between List and Tuple datatype(including example). 2
2. a) Differentiate between file modes r+ and w+ with respect to Python(include example also). 2
b) Write the output of the following Python program code: 3
def ChangeList(): L=[ ]
L1=[ ]
L2=[ ]
for i in range(1,10):
L.append(i)
for i in range(10,1,–2): L1.append(i)
for i in range(len(L1)): L2.append(L1[i]+L[i])
L2.append(len(L)-len(L1)) print(“the new list is “,L2)
ChangeList()

c) Study the following program and select the possible output(s) from the options (i) to (iv) following it. Also,
write the maximum and the minimum values that can be assigned to the variable Y. 2
import random
X= random.random( ) Y= random.randint(0,4)

print(int(X),":",Y+int(X))
(i) 0 : 0 (ii) 1 : 6 (iii) 2 : 4 (iv) 0 : 3
d) Write the definition of a function Reverse(X) in Python to display the elements in reverse order such that
each displayed element is twice of the original element (element *2) of the List X in the following
manner: 3
Example: If List X contains 7 integers as follows:
X[0] X[1] X[2] X[3] X[4] X[5] X[6] 4 8 7 5 6 2 10
After executing the function, the List content should be displayed as follows: 20 4 12 10 14 16 8
e) Observe the following code and answer the questions that follow: 2

File = open("datafile","a") File.close()


(i) What type (Text/Binary/CSV) of file is datafile?

#Blank1
(ii) Fill in Blank1 with a statement to write string “File containing data” in the file “datafile”.
f) Consider the following unsorted list: 95 79 19 43 52 3. Write the passes of bubble sort for sorting the list in
ascending order till the 3rd iteration or till III pass. 3
g) Write a program to write a string in the binary file “comp.dat” and count the number of times a character
appears in the given string using a dictionary. 3
SECTION B : Database Concepts & Computer Networks(30 marks)

3 a) Observe the table ‘Club’ given below and answer the questions: 1x2=2 Club
Member_id Member_Name Address Age Hobby Fee
M002 Nisha Gurgaon 19 Computer 3500
M003 Niharika New Delhi 21 dance 2100
M004 Sachin Faridabad 18 Sports 3500
(i) What is the cardinality and degree of the above given table?
(ii) If a new column contact_no has been added and three more members joined the club, then how these
changes will affect the degree and cardinality of the above given table.

b) Table COACHING is shown below. Write commands in SQL for (i) to (iii) and output for
(iv) and (v) 1x4=4
ID NAME AGE CITY FEE PHONE
P1 SAMEER 34 DELHI 45000 9811076656
P2 ARYAN 35 MUMBAI 54000 9911343989
P4 RAM 34 CHENNAI 45000 9810593578
P6 PREMLATA 36 BHOPAL 60000 9910139987
P7 SHIKHA 36 INDORE 34000 9912139456
P8 RADHA 33 DELHI 23000 8110668888
(i) Write a query to display name in descending order whose age is more than 23.
(ii) Write a query to find the average fee agewise from the table.
iii) Write query details from coaching table where fee is between 30000 and 40000.
iv) Select sum(Fee) from coaching where city like “%E% ;
v) Select name, city from coaching group by age having count(age)>2;
c) Write full form of DML. 1

4 a) Identify the errors in the following query and correct it: 1x2=2
i. Select * from Student where Name = NULL;
ii. Select max(salary) from employee group by designation where DOJ > "2020-02-02";

b) Write SQL commands for the queries (i) to (ii) and output for (iii) to (iv) based on the tables ‘Watches’ and
‘Sale’ given below:
Watches
Watchid Watch_Name Price Type Qty_Store
W001 High Time 10000 Unisex 100
W002 Life Time 15000 Ladies 150
W003 Wave 20000 Gents 200
W004 High Fashion 7000 Unisex 250
W005 Golden Time 25000 Gents 100
Sale
Watchid Qty_Sold Quarter Profit
W001 10 1 1200
W003 5 1 1000
W002 20 2 5000
W003 10 2 1500
W001 15 3 1500
W002 20 3 5000
W005 10 3 1000

W003 15 4 2000
(i) To display total quantity in store of Unisex type watches along with Profit. 2
(ii) To display watch name and their quantity sold in first quarter. 2
(iii) select watch_name,price,profit from watches w, sale s where w.watchid=s.watchid ; 1
(iv) select watch_name, qty_store, sum(qty_sold), qty_store-sum( qty_sold) “Stock” from watches w, sale s
where w.watchid=s.watchid group by s.watchid ; 1
5 a) Name any two threats to computer security. 1
b) Write any two characteristics of Iot. 1
c) Write any one advantage and disadvantage of Coaxial cable. 2
d) Riana Medicos Centre has setup its new centre in Dubai.It has four buildings as shown in the diagram given
below:
Distances between various buildings are as follows:
Accounts to Research Lab 55m Accounts to Store 150m
Store to Packaging Unit 160m Packaging Unit to Research Lab 60m Accounts to Packaging Unit 125m Store
to Research Lab 180m
Number of computers:
Accounts 25 Research Lab 100
Store 15 Packaging Unit 60
As a network expert, provide the best possible answer for the following queries: 1x4=4
(i) Suggest the type of network established between the buildings.
(ii) Suggest the most suitable place (i.e., building) to house the server of this organization.
(iii) Suggest the placement of the following devices with justification: (a)Repeater (b)Hub/Switch
(iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the network.
6 a) Name different types of network depending upon geographical location. 1
b) Expand the term: MAC 1
c) What is the importance of URL in networking? 1
d) Ayurveda Training Educational Institute is setting up its centre in Hyderabad with four specialised
departments for Orthopedics, Neurology and Pediatrics along with an administrative

office in separate buildings. The physical distances between these department buildings and the number of
computers to be installed in these departments and administrative office are given as follows.
Shortest distances between various locations in metres :

Number of Computers installed at various locations are as follows :


You, as a network expert, have to answer the queries as raised by them in (i) to (iv): 1X4=4
i) Suggest the most suitable location to install the main server of this institution to get efficient connectivity.
ii) Suggest the best cable layout for effective network connectivity of the building having server with all the
other buildings(also show the topology layout).
iii) Suggest the devices to be installed in each of these buildings for connecting computers installed within the
building out of the following :
Gateway, switch, Modem
iv) Suggest the topology of the network and network cable for efficiently connecting each computer installed in
each of the buildings out of the following :
Topologies : Bus Topology, Star Topology
Network Cable : Single Pair Telephone Cable, Coaxial Cable, Ethernet Cable/ Coaxial

SECTION C : MCQ( 10 marks)

7. Choose the correct option for the following(i - xx) : (.5x20=10)

i) What is the output of the function shown below? import math


abs(math.sqrt(25))
a) Error b) -5 c) 5 d) 5.0

ii) Observe the following table CANDIDATE carefully and write the name of the RDBMS operation out of the
following : \
TABLE: CANDIDATE
NO NAME STREAM
C1 AJAY LAW
C2 ADITI MEDICAL
C3 ROHAN EDUCATION
C4 RISHAB ENGINEERING
a) SELECTION b) PROJECTION
c) UNION d) CARTESIAN PRODUCT which has been used to produce the output as shown in RESULT ?
RESULT
NO NAME Stream
C2 ADITI Medical

iii) Which of the following is the use of function in python?


a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned

iv) What is the output of the below program? def printMax(a, b):
if a > b:
print(a, 'is maximum') elif a == b:
print(a, 'is equal to', b)

else:
print(b, 'is maximum') printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned

v) What is the output of below program? def f(x, y, z):


return x + y + z f(2, 30, 400)
a) 432 b) 24000 c) 430 d) No output

vi) Scalar functions are also known as :


(a) Single row function (b) Multiple row functions
(c) Group functions (d) None

vii) What is the output of this code? def f():


x=4 x=1
f()
a) Error b) 4 c) Junk value d) 1

viii) is a device that forwards data packets along networks.


a) Router b) Gateway c) Bridge d) Hub
ix) Which transmission media provides the highest transmission speed in a network?
a) Coaxial b) twisted pair c) optical fibre d) electrical cable

x) IPR Issues involve


a) Music work b) Artistic work c) Literature work d) Official work

xi) Data communication system within a building or campus is known as


a) PAN b) LAN c) MAN d) WAN

xii) Identify Network advantages:


a) Resource sharing b) Improved communication c)Reduced communication cost d) All of these

xiii) Consider a relation/table EMP & DEPT and give the correct answer of following :
Relation EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20
7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.0 30
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10
7788 SCOTT ANALYST 7566 1982-12-09 3000.00 NULL 20
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10
7844 TURNE SALESMAN 7698 1981-09-08 1500.00 0.00 30
7876 ADAMS CLERK 7788 1983-01-12 1100.00 NULL 20
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10

Relation: DEPT DEPTNO DNAME LOC


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

1. SELECT AVG(SAL) FROM EMP WHERE JOB = ‘CLERK’;

(a) 1037.5

(b) 2073.21

(c) 1040 (d) 2074

2. SELECT COUNT(*) FROM EMP WHERE DEPTNO = 10;


(a) 14 (b) 3 (c) 4 (d) 5
3. SELECT COUNT(DISTINCT JOB ) FROM EMP;
(a) 14 (b) 5 (c) 4 (d) 6
4. SELECT COUNT(ALL JOB ) FROM EMP;
(a) 14 (b) 5 (c) 4 (d) 6
5. SELECT MAX(SAL) FROM EMP WHERE JOB = ‘MANAGER’;
(a) 2975 (b) 5000 (c) 3000 (d) 2850
6. SELECT MIN(HIREDATE) FROM EMP;
(a) 1980-12-17 (b) 1983-01-12 (c) 1982-12-09 (d) None

7. SELECT MAX(HIREDATE) FROM EMP;


(a) 1980-12-17 (b) 1983-01-12 (c) 1982-12-09 (d) None

8. SELECT SUM(COMM) FROM EMP;


(a) Null (b) 0 (c) 2200 (d) 1400

a) Which command is used to create structure of the table?

b) Which aggregate function is used to find average value of a particular column

c) Which clause is used to enables SQL aggregate functions for grouping of information.

d) What is the importance of primary key in a table? Explain with suitable example.

e) Differentiate between union and Cartesian product.

Write a output for SQL queries (i) to (iii), which are based on the tables:

TABLE : ACCOUNT
ANO ANAME ADDRESS
101 Nirja Singh Bangalore
102 Rohan Gupta Chennai
103 Ali Reza Hyderabad
104 Rishabh Jain Chennai
105 Simran Kaur Chandigarh

TABLE : TRANSACT
TRNO ANO AMOUNT TYPE DOT
T001 101 2500 Withdraw 2017-12-21
T002 103 3000 Deposit 2017-06-01
T003 102 2000 Withdraw 2017-05-12
T004 103 1000 Deposit 2017-10-22
T005 101 12000 Deposit 2017-11-06
i) SELECT ANO, ANAME FROM ACCOUNT WHERE ADDRESS NOT IN ('CHENNAI', 'BANGALORE');
ii) SELECT DISTINCT ANO FROM TRANSACT;
iii) SELECT ANO, COUNT(*), MIN(AMOUNT) FROM TRANSACT GROUP BY ANO HAVING
COUNT(*)> 1;

#-------------------------------------------------------------------------------------------------------------------------------------
--
Find errors:
#-------------------------------------------------------------------------------------------------------------------------------------
--
input('Enter a word',w)
if w = 'Hello'
print('ok')
else:
print('Not ok')
#-------------------------------------------------------------------------------------------------------------------------------------
--

def ChangeVal(M,N):
for i in range(N):
if M[i]%5==0:
M[i] //=5
if M[i]%3==0:
M[i] //=3

L=[25,8,75,12]
ChangeVal(L,4)
for i in L:
print(i,end='#')

#---------------------------------------------------------------------------------------------------------------------------------

def Call(P=40,Q=20):
P=P+Q
Q=P-Q
print(P,'@',Q)
return P

R = 200
S= 100
R = Call(R,S)
print(R,'@',S)
S = Call(S)
#print(R,'@',S)

#------------------------------------------------------------------------------------------------------

import random
colours = ['VIOLET','INDIGO','BLUE','GREEN','YELLOW','ORANGE','RED']
End = random.randrange(2) + 3
Begin = random.randrange(End) + 1

for i in range(Begin,End):
print(colours[i],end='&')

#-----------------------------------------------------------------------------------------------------------
for i in range(2,7,3):
print(i,'$')

def Update(X=10):
X += 15
print('X = ',X)

X = 20
Update()
print('X = ',X)

x = ['ab', 'cd']
for i in x:
x.append(i.upper())
print(x)

Write functions in Python for InsertQ(Names) and for RemoveQ(Names) for performing insertions and removal
operations with a queue of List contains names of students.

Write a function in python to count the number of words in a text file ‘STORY.TXT’ which is starting with an
alphabet ‘a’.

Write a function in python to read lines from a text file STORY.TXT, and display those lines, which are not
starting with
alphabet ‘A’.

Write a function in Python, INSERTQ(Arr,data) and DELETEQ(Arr) for performing insertion and deletion
operations in a Queue.
Arr is the list used for implementing queue and data is the value to be inserted.

Write a function in python, MakePush(Package) and MakePop(Package) to add a new Package and delete a
Package from a List of
Package. Description, considering them to act as push and pop operations of the Stack data structure.

You might also like