You are on page 1of 39

GBSSS.GOKALPUR.

VILL
AGE
COMPUT
Python
ER
Programs and
SCIENCE
SQL Queries
PRACTIC
AL FILE

Name : Harshit Panchal


Class : 12th ‘A’
Roll no. : 12120
Subject : Computer Science
Submitted to : Mohit Giri (TGT)
Date : ___________

2
s.no. Topic Date Page no. Signature
1. type value to a CONTENTS
Python program to pass a mutable

function(Adding/Deleting item to it)


3

2. Output of Program 1 4
Python program to delete an element
3. from a sorted linear list 5
4. Output of Program 2 6
Python program to print a fibonacci
5. series upto n terms using recursion 7
6. Output of Program 3 8
python program to print sum of first
7. n natural numbers using recursion 9
8. Output of Program 4 10
python program to find factorial of
9. a number 11
10. Output of Program 5 12
Python program to find the sum of
11. all the elements of a list 13
12. Output of Program 6 14
Read a text file line by line and
13. display each word separated by a ‘#’ 15
14. Output of Program 7 16
Read a text file and display the
number of vowels, consonants, 17
15. uppercase and lowercase characters
in the file
16. Output of Program 8 18
Remove all the lines that contain
17. the character ’a’ in a file and 19
write it to another file
18. Output of Program 9 20
Create a binary file with name and
roll number, Search for a given roll 21
19. number and display the name, if not
found display appropriate message
20. Output of Program 10 22
Create a binary file with roll
21. number, name and marks. Input a roll 23
number and update the marks
22. Output of Program 11 24
Write a random number generates
23. random numbers between 1 and 6 25
(simulates to dice)
24. Output of Program 12 26
Write a python program to implement
25. a stack using list 27,28
26. Output of Program 13 29
Create a CSV file by entering User-
27. ID and password read and search 30
password
28. Output of Program 14 31
Integrate SQL with python by 32-33

2|Page
Date : ___________

3
29. importing suitable module
Create a student table and insert
30. data 35-36
31. UPDATE table to modify data 37-38
ALTER table to add new
32. attributes/modify data type/drop 39
attribute
ORDER BY to display data in 40
33. ascending/descending order
34. DELETE to remove table(s) 41
GROUP BY and find the min, max, sum,
35. count and average 42

Python Program No. 1


Python program to pass a mutable type value to a
function(Adding/Deleting item to it)

3|Page
Date : ___________

4
def myFunc3(myList):
print("\t Inside CALLED Function now")
print("\t List Recieved :",myList)
myList.append(2)
myList.extend([5,1])
print("\t List after adding some elements :",myList)
myList.remove(5)
print("\t List within called function,after all changes",myList)
return

List1=[1]
print("List before function call :",List1)
myFunc3(List1)
print("List after function call :",List1)

Output of Program 1

4|Page
Date : ___________

Python Program No. 2


Python program to delete an element from a sorted
linear list

num=int(input("Enter any number : "))


if num>1:
for i in range(num,num+1):
if(num%i)==0:

5|Page
Date : ___________

6
print(num,"is NOT a prime number")
break
else:
print(num,"is a prime number")
elif num==0 or 1:
print(num,"is neither a prime number and nor a composite number")
else:
print(num,"is not a prime number...It is a composite number")

Output of Program 2

6|Page
Date : ___________

Python Program No. 3


Python program to print a fibonacci series upto n
terms using recursion

def fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
#___main___
n=int(input("Enter number to print fibonacci series upto : "))
for i in range(n):
print(fib(i),end='\t')

7|Page
Date : ___________

Output of Program 3

8|Page
Date : ___________

Python Program No. 4


python program to print sum of first n nautral numbers
using recursion

def sum(n):
if n==1:
return 1
else:
return n+sum(n-1)
num=int(input("Enter number upto which you want to print sum : "))
if num <=0:
print("Not a Natural Number!!!...")
else:
print("The sum of series = ",sum(num))

9|Page
Date : ___________

10

Output of Program 4

10 | P a g e
Date : ___________

11

Python Program No. 5


python program to find factorial of a number

def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
num = int(input("Enter a number : "))
if num<0:
print("SORRY...Factorial can't be calculatrd for negative numbers")
else:
print("The factorial of ",num,'is',factorial(num))

11 | P a g e
Date : ___________

12

Output of Program 5

12 | P a g e
Date : ___________

13

Python Program No. 6


Python program to check a string is a palindrome or
not

original=input("Enter any String : ")


reverse=original[::-1]
if original==reverse:
print("String is a palindrome...")
else:
print("String is not a palindrome...")

13 | P a g e
Date : ___________

14

Output of Program 6

14 | P a g e
Date : ___________

15

Python Program No. 7


Read a text file line by line and display each word
separated by a ‘#’

file = open("story.txt","r")
readLine = file.readlines()
for i in readLine:
words = i.split()
for a in words:
print(a+"#",end = "")

file.close()

15 | P a g e
Date : ___________

16

Output of Program 7

Python Program No. 8

16 | P a g e
Date : ___________

17
Read a text file and display the number of vowels,
consonants, uppercase and lowercase characters in the
file

def function():
file = open("story.txt","r")
readLine = file.readline()
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
for i in readLine:
if (i == 'a' or i == 'e' or i =='i' or i =='o' or i =='u' or i =='A'
or i == 'E' or i =='I' or i =='O' or i =='U'):
vowels = vowels + 1
else:
consonants = consonants + 1
if (i.isupper()):
uppercase = uppercase + 1
else:
lowercase = lowercase + 1

print("Number of vowels are :",vowels,end = ",")


print("Number of consonants are :",consonants,end = ",")
print("Number of lowercase are :",uppercase,end = ",")
print("Number of uppercase are :",lowercase,end = ",")
function()

Output of Program 8

17 | P a g e
Date : ___________

18

Python Program No. 9


Remove all the lines that contain the character ’a’ in
a file and write it to another file

def remove():
file = open("story.txt","r")
lines = file.readlines()
fileold = open("story.txt","w")

18 | P a g e
Date : ___________

19
filenew = open("file with a.txt","w")
#<file with a> is a new empty file
for word in lines:
if 'a' in word:
filenew.write(word)
else:
fileold.write(word)
print("File <Story> and <File with a> both updated....")

remove()

Output of Program 9
Before:

19 | P a g e
Date : ___________

20

After:

Python Program No. 10


Create a binary file with name and roll number, Search
for a given roll number and display the name, if not
found display appropriate message

import pickle
def write():
D={}
f=open("studentdetail.dat","wb")
while True :
r=int(input("Enter roll no. : "))
n=input("Enter name : ")
D['Rollno']=r
D['Name']=n
pickle.dump(D,f)
ch=input("Do you want to add more ?<y for YES/n for NO> : ")
if ch in'Nn':
break

20 | P a g e
Date : ___________

21
f.close()
def search():
found=0
rollno=int(input("ENTER ROLL NO. TO FIND : "))
f=open("studentdetail.dat","rb")
try:
while True:
rec=pickle.load(f)
if rec['Rollno']==rollno:
print(rec['Name'])
found=1
break
except EOFError:
f.close
if found==0:
print("SORRY...NO RECORD FOUND")
write()
search()

Output of Program 10

21 | P a g e
Date : ___________

22

Python Program No. 11


Create a binary file with roll number, name and marks.
Input a roll number and update the marks

import pickle
def write():
f = open("studentdetail.dat",'wb')
while True:
r=int(input("Enter Roll No. : "))
n=input("Enter Student Name : ")
m=int(input("Enter marks of Student : "))
record=[r,n,m]
pickle.dump(record,f)
ch=input("Do you want to add more records ? ")
if ch in 'Nn':
break
f.close()
def read():
f = open("studentdetail.dat",'rb')
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def update():
22 | P a g e
Date : ___________

23
f = open("studentdetail.dat",'rb+')
rollno=int(input("Enter roll no. whose marks you want to Update"))
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[0]==rollno:
marks=int(input("Enter Updated Marks : "))
rec[2]=marks
f.seek(pos)
pickle.dump(rec,f)
except EOFError:
f.close()
write()
read()
update()
read()

Output of Program 11

23 | P a g e
Date : ___________

24

Python Program No. 12


Write a random number generates random numbers between
1 and 6 (simulates to dice)

import random
while True:
print("======================================================")
print("::::::::::::::::::::::ROLLING DICE::::::::::::::::::::")
print("======================================================")
num=random.randint(1,6)
if num == 6:
print("Hey you got",num,"...Congratulations...")
elif num == 1:
print("Well Tried...But you got",num)
else:
print("You got",num)
ch= input("Want to roll Dice Again ?")
if ch in 'Nn':
break
print("Thanks for Playing........")

24 | P a g e
Date : ___________

25

Output of Program 12

25 | P a g e
Date : ___________

26

Python Program No. 13


Write a python program to implement a stack using list
print("##############:___STACK IMPLEMENTATION___:##############")
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isEmpty(stk):
return"UNDERFLOW"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isEmpty(stk):
return"UNDERFLOW"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])
#___main___
stack=[]
top=None
while True:
print('''STACK OPERATIONS
1. PUSH
2. POP
3. PEEK
26 | P a g e
Date : ___________

27
4. DISPLAY STACK
5. EXIT''')
ch = int(input("Enter operation of your choice(1-5) : "))
if ch == 1:
item=int(input("Enter item : "))
push(stack,item)
elif ch == 2:
item=pop(stack)
if item =="UNDERFLOW":
print("UNDERFLOW!!! Stack is empty!")
else:
print("Popped item is",item)
elif ch == 3:
item=peek(stack)
if item == "UNDERFLOW":
print("UNDERFLOW!!! Stack is empty!")
else:
print("Topmost item is",item)
elif ch == 4:
display(stack)
elif ch == 5:
break
else:
print("Invalid Choice!")

27 | P a g e
Date : ___________

28

Output of Program 13

28 | P a g e
Date : ___________

29

Python Program No. 14


Create a CSV file by entering User-ID and password
read and search password

import csv
def write():
f = open("detail.csv",'w',newline='')
obj=csv.writer(f)
obj.writerow(["UserID","Password"])
while True:
u_id=input("Enter User ID : ")
pswd=input("Enter Password : ")
data=[u_id,pswd]
obj.writerow(data)
ch=input("Do you want to add more records ?")
if ch in 'Nn':
break
f.close()
def read():
f = open("detail.csv",'r')
readobj=csv.reader(f)
for i in readobj:
print(i)
f.close()
def search():
f=open("detail.csv","r")
found=0
u=input("Enter USER ID to search : ")
readobj=csv.reader(f)
next(readobj)
for i in readobj:
if i[0]==0:
print(i[1])
found=1
if found == 0:
print("Sorry... No record found..")
f.close()
write()
read()
search()

29 | P a g e
Date : ___________

30

Output of Program 14

Python

Python Program No. 15


30 | P a g e
Date : ___________

31
>>>import mysql.connector as sqltor
>>>mycon = sqltor.connect(host = "localhost", user = "root", passwd =
"MyPass", database = "school")
>>>cursor = mycon.cursor()
>>>cursor.execute("create database school")
>>>for db in cursor:
... print(db)
...
>>>cursor.execute(“ show databases “)
>>>for db in cursor:
... print(db)
>>>cursor.execute(“ use school “)
>>>cursor. execute( " CREATE TABLE students ( stud_id varchar(200), stud_name
VARCHAR(215), address VARCHAR(215), city char(100)) " )
>>> cursor. execute( " CREATE TABLE department ( dept_id varchar(200),
dept_name VARCHAR(215)) " )
>>> cursor.execute( "CREATE TABLE faculty ( faculty_id
varchar(200),faculty_name VARCHAR(215) )" )
>>> cursor. execute ( " show tables " )
>>> for x in cursor:
... print(x)
...
>>>cursor.execute( " ALTER TABLE students ADD COLUMN id INT AUTO_INCREMENT
PRIMARY KEY " )
>>> cursor.execute("desc students")
>>> for x in cursor:
... print(x)
...
>>> stm = " INSERT INTO students ( stud_id, stud_name, address, city ) VALUES
('101','Dheeraj', 'Shiv vihar', 'UTTAR PRADESH' ) "
>>> cursor = my_database.cursor()
>>> cursor.execute(stm)
>>> cursor.execute(" select * from students")
>>> for x in cursor:
... print(x)
...
>>> cursor.fetchall()

DATABASE MANAGEMENT
31 | P a g e
Date : ___________

32

MySQL Query
Create a student table and insert data

create database GBSSS;


Query OK, 1 row affected (0.00 sec)
Use GBSSS;
Database changed
create table school(Roll_no int(12) primary key not null, Name varchar(255)
not null, Stream varchar(255) not null, marks int not null);
Query OK, 0 rows affected (0.01 sec)
insert into school values(1,'Raj','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(2,'Vipin','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(3,'Nakul','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(4,'Ishu','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(5,'Dheeraj','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(6,’Tushar Ruhela','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(7,'Aryan','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(8,'Atul','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(9,'Harsh Vishwakarma','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(10,’Harsh Dubey','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(11,'Harshit Panchal','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(12,'Ved Panchal','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(13,'Vishal','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(14,'Sumit','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(15,'Prashant Yadav','PCM',92);
Query OK, 1 row affected (0.00 sec)
insert into school values(16,'Vivek','PCM',92);
Query OK, 1 row affected (0.00 sec)

Output of MySQL Query


32 | P a g e
Date : ___________

33

select * from school;


+------------+-------------------+--------+-------+
| Roll_no | Name | Stream | marks |
+------------+-------------------+--------+-------+
| 1 | Raj | PCM | 92 |
| 2 | Vipin | PCM | 92 |
| 3 | Nakul | PCM | 92 |
| 4 | Ishu | PCM | 92 |
| 5 | Dheeraj | PCM | 92 |
| 6 | Tuhar Ruhela | PCM | 92 |
| 7 | Aryan | PCM | 92 |
| 8 | Atul Sharma | PCM | 92 |
| 9 | Harsh Vishwakarma | PCM | 92 |
| 10 | Harsh Dubey | PCM | 92 |
| 11 | Harsit Panchal | PCM | 92 |
| 12 | Ved Panchal | PCM | 92 |
| 13 | Vishal | PCM | 92 |
| 14 | Sumit | PCM | 92 |
| 15 | Prashant Yadav | PCM | 92 |
| 16 | Vivek | PCM | 92 |
+------------+-------------------+--------+-------+
16 rows in set (0.00 sec)

MySQL Query 1
33 | P a g e
Date : ___________

34

UPDATE table to modify data

Mysql> update school


-> set marks=87
-> where name='ishu';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0

mysql> update school


-> set marks=91
-> where name='vipin';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update school


-> set marks=90
-> where name='nakul';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update school


-> set marks=86
-> where name='harsh vishwakarma';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update school


-> set name = 'prashant yadav'
-> where name='pradhant yadav';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Output of MySQL Query 1


34 | P a g e
Date : ___________

35

mysql> select * from school;


+------------+-------------------+--------+-------+
| Student_ID | Name | Stream | marks |
+------------+-------------------+--------+-------+
| 1 | Ishu | PCM | 87 |
| 2 | Vipin | PCM | 91 |
| 3 | Nakul | PCM | 90 |
| 4 | Harsh Vishwakarma | PCM | 86 |
| 5 | prashant yadav | PCM | 92 |
| 6 | Shivam kr. | PCM | 92 |
| 7 | vivek | PCM | 92 |
| 8 | mukesh | PCM | 92 |
| 9 | Govind Shukla | PCM | 92 |
| 10 | Harsh Dubey | PCM | 92 |
| 11 | Manoj | PCM | 92 |
| 12 | Jatin Bhatt | PCM | 92 |
| 13 | Shivank Malik | PCM | 92 |
| 14 | Tarun | PCM | 92 |
| 15 | Vivek | PCM | 92 |
| 16 | Himanshu | PCM | 92 |
| 17 | Tushar Ruhela | PCM | 92 |
| 18 | Atul Sharma | PCM | 92 |
| 19 | Harshit Panchal | PCM | 92 |
| 20 | Nikhil | PCM | 92 |
| 21 | Vishal | PCM | 92 |
| 22 | Shubham | PCM | 92 |
| 23 | Hasnain | PCM | 92 |
| 24 | Himanshu | PCM | 92 |
| 25 | Raj | PCM | 92 |
| 26 | Ved | PCM | 92 |
+------------+-------------------+--------+-------+
26 rows in set (0.00 sec)

MySQL Query 2
35 | P a g e
Date : ___________

36

ALTER table to add new attributes/modify data


type/drop attribute

mysql> alter table school


-> add (Result varchar(255) not null);
Query OK, 26 rows affected (0.01 sec)
Records: 26 Duplicates: 0 Warnings: 0
mysql> select * from school;
+------------+-------------------+--------+-------+--------+
| Roll_No | Name | Stream | marks | Result |
+------------+-------------------+--------+-------+--------+
| 1 | Ishu | PCM | 87 | pass |
| 2 | Vipin | PCM | 91 | pass |
| 3 | Nakul | PCM | 90 | pass |
| 4 | Harsh Vishwakarma | PCM | 86 | pass |
| 5 | prashant yadav | PCM | 92 | pass |
| 6 | Shivam kr. | PCM | 87 | pass |
| 7 | vivek | PCM | 90 | pass |
| 8 | mukesh | PCM | 89 | pass |
| 9 | Govind Shukla | PCM | 90 | pass |
| 10 | Harsh Dubey | PCM | 88 | pass |
| 11 | Manoj | PCM | 87 | pass |
| 12 | Jatin Bhatt | PCM | 90 | pass |
| 13 | Shivank Malik | PCM | 91 | pass |
| 14 | Tarun | PCM | 92 | pass |
| 15 | Vivek | PCM | 90 | pass |
| 16 | Himanshu | PCM | 79 | pass |
| 17 | Tushar Ruhela | PCM | 84 | pass |
| 18 | Atul Sharma | PCM | 87 | pass |
| 19 | Harshit Panchal | PCM | 81 | pass |
| 20 | Nikhil | PCM | 88 | pass |
| 21 | Vishal | PCM | 90 | pass |
| 22 | Shubham | PCM | 78 | pass |
| 23 | Hasnain | PCM | 87 | pass |
| 24 | Himanshu | PCM | 89 | pass |
| 25 | Raj | PCM | 95 | pass |
| 26 | Ved | PCM | 86 | pass |
+------------+-------------------+--------+-------+--------+
26 rows in set (0.00 sec)

MySQL Query 3
36 | P a g e
Date : ___________

37

ORDER BY to display data in ascending/descending order

mysql> select name from school


-> order by name;
+-------------------+
| name |
+-------------------+
| Atul Sharma |
| Govind Shukla |
| Harsh Dubey |
| Harsh Vishwakarma |
| Harshit Panchal |
| Hasnain |
| Himanshu |
| Himanshu |
| Ishu |
| Jatin Bhatt |
| Manoj |
| mukesh |
| Nakul |
| Nikhil |
| prashant yadav |
| Raj |
| Shivam kr. |
| Shivank Malik |
| Shubham |
| Tarun |
| Tushar Ruhela |
| Ved |
| Vipin |
| Vishal |
| Vivek |
| vivek |
+-------------------+
26 rows in set (0.00 sec)

MySQL Query 4
37 | P a g e
Date : ___________

38

DELETE to remove table(s)

mysql> drop table school;


Query OK, 0 rows affected (0.00 sec)

MySQL Query 5
38 | P a g e
Date : ___________

39

GROUP BY and find the min, max, sum, count and average
mysql> select name,marks
-> from school
-> where marks>=87
-> group by marks;
+----------------+-------+
| name | marks |
+----------------+-------+
| Ishu | 87 |
| Harsh Dubey | 88 |
| mukesh | 89 |
| Nakul | 90 |
| Vipin | 91 |
| prashant yadav | 92 |
| Raj | 95 |
+----------------+-------+
7 rows in set (0.00 sec)
mysql> select max(marks) from school;
+------------+
| max(marks) |
+------------+
| 95 |
+------------+
1 row in set (0.00 sec)

mysql> select min(marks) from school;


+------------+
| min(marks) |
+------------+
| 78 |
+------------+
1 row in set (0.00 sec)
mysql> select count(student_id) from school;
+-------------------+
| count(student_id) |
+-------------------+
| 26 |
+-------------------+
1 row in set (0.00 sec)
mysql> select avg(student_id) from school;
+-----------------+
| avg(student_id) |
+-----------------+
| 13.5000 |
+-----------------+
1 row in set (0.00 sec)

39 | P a g e

You might also like