Booklet XII CS 2024-25
Booklet XII CS 2024-25
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
2 Computer Networks 10
3 Database Management 20
Month Syllabus
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.
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
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
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.
10 SALES KOKATA
20 FINANCE MUMBAI
30 HR DELHI
Date_of_birth Date 10
Gender Char 1
Designation Varchar 20
Salary Integer 10
SQL - 2
Consider the following table Product. Write SQL queries for the following statements
TABLE : PRODUCT
SQL - 3
Table : TRAINER
Table : COURSE
1. Create the tables Trainer (TID is primary key) and Course (CID is primary key)
7 Arjun 043
Sharma
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
Salary Integer 10
Marks Integer 3
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
Table: ITEM
c. To display IName and Price of all the Items in ascending order of their price.
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
Table: product
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
TABLE : RECIPIENT
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())
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
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/*
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='$')
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)
print(round(3.141593))
print(round(3.141593,1))
print(round(3.141593,2))
print(round(3.141593,3))
import math
print(math.pow(3,4))
3. floor(value) - It will return the value i.e equal or lesser than the given value.
3. ceil(value) - It will return the value i.e equal or greater than the given value.
print(11/4)
print(11//4) #integer division
print(11.0//4) #integer division- float / int - float
print(-11.0//4) #integer division
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))
statistics module
mean(), median(), mode()
random module
random(),randint(),randrange(start,stop,step)
def - keyword
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 : '))
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
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
#-------------------------------------------------------------------------------------------------------------------------------------
------------
#---------------------------------------------------------------------------------
WAF to find area and perimeter of a rectangle.
#---------------------------------------------------------------------------------
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=' ')
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
#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.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
arguments/parameter
Values or variables which are provided at the time of defining or calling the function.
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
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--------------------------------------------------------------------------------------------------------
------------
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')
#-----------------------------------------------------------------------------------------------------------------------------
--------------
def strep(str):
str_lst =list(str) # convert string into list
# Iterate list
for i in range(len(str_lst)):
if str_lst[i] in 'aeiouAEIOU':
str_lst[i]='*'
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 Fibonacci(N):
first = 0
second = 1
for k in range(N):
print(first,end = ' ')
first,second = second,first+second
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
#---------------------------------------------------------------------------------
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)
#-------------------------------------------
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
A
AB
ABC
ABCD
ABCDE
for a in range(65,70):
for b in range(65,a+1,1):
print(chr(b),end='')
print()
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))
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.
#----------------------------------------------------------------------------------
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.
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).
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:
#-------------------------------------------------------------------------------------------------------------------------------------
-----------
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.
The try block lets you test a block of code for errors.
If i will write
print(x)
then output is
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:
a = [1, 2, 3]
try:
print ("Second element = ",a[1])
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")
Example :
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
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"
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='%')
print('Welcome')
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.
output
Enter First No : 8
Enter Second No : 4
Enter third No : 13
Largest No : 13
Smallest No : 4
result = 1
for k in range(n):
result = result * x
print('Without exponent and pow( ) function x^n = ',result)
output
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
output
(b). 1-x+x2-x3+x4-.............xn
output
Enter the value of x : 2
Enter the value of n: 5
Sum of series : -21
(c) -x + x2 - x3 + x4 - .............xn
output
Enter the value of x : 3
Enter the value of n: 4
Sum of series : 60
—------------------------------------------------------------------------------------------------------------------
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
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
File_Object = open(filename,mode)
a - append
It will add the data in the end of file(previous data remains unchanged)
if not exist then create a new file
file_object.close()
Syntax:
File_object.write(string)
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.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)
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...............')
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.
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 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 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
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
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()
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 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()
#----------------------------------------------------------------------------------
Create()
Display()
Longest_Line()
#------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------
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()
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()
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
return large_line
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').
#-----------------------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.
a=5
print(type(a))
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.
In Python, 'Binary files' can be created using pickle,JSON(Java Script Object Notation) or cpickle modules.
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).
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.
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)
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#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
#-------------------------------------------------------------------------------------------------------------------------------------
------
#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)
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
#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)
for k in data:
if Rno == k[0]:
print('Name :',k[1])
print('Marks : ',k[2])
#-------------------------------------------------------------------------------------------------------------------------------------
-----
#WAF to remove the details of a student whose Rollno is specified by user. The binary file 'student.dat' is
already exist'
#-------------------------------------------------------------------------------------------------------------------------------------
--------
#----------------------------------------------------------------------------------
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])
L.append([BNO,TITLE,AUTHOR,TYPE])
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)
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:
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”.
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)
Display()
Modify()
Display()
import pickle
def Display():
with open('PRODUCT.DAT','rb') as f:
L = pickle.load(f)
print(len(L))
Display()
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
#-------------------------------------------------------------------------------------------------------------------------------------
---------------
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.
print('hi')
print("HI")
print('It"s me')
import csv
#How many ways we can import module?
import math
print(math.sqrt(81))
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=',')
1,Raj,75.5
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])
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])
#-------------------------------------------------------------------------------------------------------------------------------------
------------
#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])
#-------------------------------------------------------------------------------------------------------------------------------------
-----
#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'
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.
#-------------------------------------------------------------------------------------------------------------------------------------
------------
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)
#-------------------------------------------------------------------------------------------------------------------------------------
------------
d = {'A':30,'B':25,'C':45}
Find(d)
print(d,end='@')
Find(d,7)
print(d,end='^')
#-------------------------------------------------------------------------------------------------------------------------------------
------------
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 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?
#-------------------------------------------------------------------------------------------------------------------------------------
------------
#-------------------------------------------------------------------------------------------------------------------------------------
------------
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')
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 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
#-------------------------------------------------------------------------------------------------
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.
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(78)
del L[index]
List - search -
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
linear Search binary Search
#-------------------------------------------------------------------------------------------------------------------------------------
----------------
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]
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)
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]
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
nlist[position]=currentvalue
L = [1,2,3,2,5,4,1,2,3]
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)
#-------------------------------------------------------------------------------------------------------------------------------------
---
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.
Queue
It is a linear/sequence structure in which insertion is done from rear end and deletion is done from front end.
#-------------------------------------------------------------------------------------------------------------------------------------
-----------
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')
#--------------------------------------------------------------------------------------------------------------------------------
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
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
10. Write the function sumAlternate(MYLIST) as argument and calculate the sum of all alternate elements of
MYLIST and print it
Output should be :
Total = 133
#-------------------------------------------------------------------------------------------------------------------------------------
Python DB-API -
It is a widely used module that provides a database application programming interface.
Ex: MySQL, Oracle, Sybase, Ingres etc.
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.
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.
import mysql.connector
or
import mysql.connector as sql #sql is an alternative name
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:
Example:
mycursor = con.cursor()
4. Execute a query.
Example:
mycursor.execute('use school')
#-------------------------------------------------------------------------------------------------------------------------------------
------------------
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()
#-------------------------------------------------------------------------------------------------------------------------------------
------------------
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()
#-------------------------------------------------------------------------------------------------------------------------------------
--------------
#Insert a record in student table
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
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 : '))
#-------------------------------------------------------------------------------------------------------------------------------------
----------
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
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()
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 : '))
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.
#-------------------------------------------------------------------------------------------------------------------------------------
--------------
Display()
#-------------------------------------------------------------------------------------------------------------------------------------
-------------
1. Explain how will you extract data from a resultsheet using fetch()?
4. What is Resultset?
#--------------------------------------------------------------------------------------------------
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)")
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: '))
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
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
#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 :
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
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
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
(a) 1037.5
(b) 2073.21
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.
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.