Practical File: Computer Science
Practical File: Computer Science
PYTHON
Student Name :
Roll No. :
At & Post: Zundal, Opp. Zundal Village, Gandhinagar Contact No.: 9925991800,
Certificate
Principal
INDEX
PRACTICAL FILE- COMPUTER SCIENCE (083)
#Program
Program1: toInput
calculate
any factorial
number of entered
from usernumber
and calculate factorial of a
num =
number int(input("Enter any number :"))
fact = 1
n = num # storing num in n for printing
while num>1: # loop to iterate from n to 2
fact = fact * num
num-=1
OUTPUT
Enter any number :6
Factorial of 6 is : 720
Page : 1
Date Experiment
#Program
Program 1: toInput
inputany
any number
number from
from user
user and check it is Prime no. or not
#Check it is Prime number of not
import math
num = int(input("Enter any number :"))
isPrime=True
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
isPrime=False
if isPrime:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")
OUTPUT
Enter any number :117
## Number is not Prime ##
>>>
Enter any number :119
## Number is not Prime ##
>>>
Enter any number :113
## Number is Prime ##
>>>
Enter any number :7
## Number is Prime ##
>>>
Enter any number :19
## Number is Prime ##
Page : 2
Date Experiment No:
#Program
Program : to find asum
Write of elements
program of sum
to find list recursively
of elements of List recursively
def findSum(lst,num):
if num==0:
return 0
else:
return lst[num-1]+findSum(lst,num-1)
sum = findSum(mylist,len(mylist))
print("Sum of List items ",mylist, " is :",sum)
OUTPUT
Enter how many number :6
Enter Element 1:10
Enter Element 2:20
Enter Element 3:30
Enter Element 4:40
Enter Element 5:50
Enter Element 6:60
Sum of List items [10, 20, 30, 40, 50, 60] is : 210
Page : 3
Date Experiment No:
#Program
Program 1:toWrite
find 'n'th term of fibonacci
a program series
to calculate the nth term of Fibonacci series
#Fibonacci series : 0,1,1,2,3,5,8,13,21,34,55,89,...
#nth term will be counted from 1 not 0
def nthfiboterm(n):
if n<=1:
return n
else:
return (nthfiboterm(n-1)+nthfiboterm(n-2))
OUTPUT
Enter the 'n' term to find in fibonacci :10
10 th term of fibonacci series is : 55
Page : 4
Date Experiment No:
#Program
Program : to find thetooccurence
Program of word
search any any word in a string/sentence
in given string
def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
OUTPUT
Enter any sentence :my computer your computer our computer everyones
computer Enter word to search in sentence :computer
## computer occurs 4 times ##
Page : 5
Date Experiment No:
#Program
Program 1:to Program
read content of fileand
to read linedisplay
by line file content line by line with each
#and
word display
separatedeachbyword
„#‟ separated by '#'
f=
open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()
OUTPUT
India#is#my#country#
I#love#python#
Python#learning#is#fun#
Page : 6
Date Experiment No:
#Program
Programto1:read content of
Program tofile
read the content of file and display the total
#and display total number of vowels, consonants, lowercase and uppercase characters
number of consonants, uppercase, vowels and lower case characters‟
f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()
NOTE : if the original content of file is:
India is my country
I love python
Python learning is fun
123@
OUTPUT
Total Vowels in file : 16
Total Consonants in file n : 30
Total Capital letters in file :2
Total Small letters in file : 44
Total Other than letters :4
Page : 7
Date Experiment No:
#Program to create a binary file to store Rollno and name
#Search
Program for1:Rollno and display
Program record
to create if found
binary file to store Rollno and Name, Search
#otherwise "Roll no. not found"
any Rollno and display name if Rollno found otherwise “Rollno not found”
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
Page : 8
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Add More ?(Y)y
Page : 9
Date Experiment No:
#Program to create a binary file to store Rollno and name
#Search
Program for1:Rollno and display
Program record
to create if found
binary file to store Rollno,Name and Marks
#otherwise "Roll no. not found"
and update marks of entered Rollno
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
Page : 10
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Enter Marks :99
Add More ?(Y)y
Page : 11
Date Experiment No:
#Program to read line from file and write it to another line
#Except
Program for1:those line which
Program contains
to read letter 'a'of file line by line and write it to
the content
another file except for the lines contains „a‟ letter in it.
f1 = open("file2.txt")
f2 = open("file2copy.txt","w")
OUTPUT
Page : 12
Date Experiment No:
Page : 13
Enter Employee Number 1
## Data Saved... ##
Add More ?y
## Data Saved... ##
Add More ?y
## Data Saved... ##
Add More ?n
============================
NAME : Sunil
SALARY : 80000
============================
NAME : Satya
SALARY : 75000
==========================
==========================
Page : 14
Date Experiment No:
# Program to generate random number between 1 - 6
#Program
To simulate the dice to generate random number 1-6, simulating a dice
1: Program
import random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break
OUTPUT
4Your Number is : 4
Play More? (Y) :y
Your Number is : 3
Play More? (Y) :y
Your Number is : 2
Play More? (Y) :n
Page : 15
Date Experiment No:
def isEmpty(S):
Program 1: Program to implement Stack in Python using List
if len(S)==0:
return True
else:
return False
def Push(S,item):
S.append(item)
top=len(S)-1
def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val
def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]
def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
Page : 16
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
break
OUTPUT
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :10
Cont…
Page : 17
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :20
Page : 18
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 20 <== 10 <==
Page : 19
Date Experiment No:
def isEmpty(Q):
Program 1: Program to implement Queue in Python using List
if len(Q)==0:
return True
else:
return False
def Enqueue(Q,item):
Q.append(item)
if len(Q)==1:
front=rear=0
else:
rear=len(Q)-1
def Dequeue(Q):
if isEmpty(Q):
return "Underflow"
else:
val = Q.pop(0)
if len(Q)==0:
front=rear=None
return val
def Peek(Q):
if isEmpty(Q):
return "Underflow"
else:
front=0
return Q[front]
def Show(Q):
if isEmpty(Q):
print("Sorry No items in Queue ")
else:
t = len(Q)-1
print("(Front)",end=' ')
front = 0
i=front
rear = len(Q)-1
while(i<=rear):
print(Q[i],"==>",end=' ')
i+=1
print()
Cont…
Page : 20
Q=[] #Queue
front=rear=None
while True:
print("**** QUEUE DEMONSTRATION ******")
print("1. ENQUEUE ")
print("2. DEQUEUE")
print("3. PEEK")
print("4. SHOW QUEUE ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Insert :"))
Enqueue(Q,val)
elif ch==2:
val = Dequeue(Q)
if val=="Underflow":
print("Queue is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(Q)
if val=="Underflow":
print("Queue Empty")
else:
print("Front Item :",val)
elif ch==4:
Show(Q)
elif ch==0:
print("Bye")
break
OUTPUT
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :1
Enter Item to Insert :10
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :1 Cont…
Page : 21
Enter Item to Insert :20
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :1
Enter Item to Insert :30
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :4
(Front) 10 ==> 20 ==> 30 ==>
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :3
Front Item : 10
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :2
Deleted Item was : 10
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :4
(Front) 20 ==> 30 ==>
**** QUEUE DEMONSTRATION ******
1. ENQUEUE
2. DEQUEUE
3. PEEK
4. SHOW QUEUE
0. EXIT
Enter your choice :0
Bye
Page : 22
Date Experiment No:
#Program to take 10 sample phishing mail
#and count1:the
Program most commonly
Program occuring
to take 10 sampleword
phishing email, and find the most
phishingemail=[
common word occurring
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)
OUTPUT
Page : 23
Date Experiment No:
Rule of Game (Total Sticks = 21):
1) User and Computer both can pick stick one by one
Program 1: Program
2) Maximum stick both to
cancreate
pick is 421i.e.Stick
1 to 4 Game so that computer always wins
3) Anyone with last stick will be the looser
def PrintStick(n):
print("o "*n)
print("| "*n)
print("| "*n)
print("| "*n)
print("| "*n)
TotalStick=21
win=False
humanPlayer=True
print("==== Welcome To Stick Picking Game :: Computer Vs User =====")
print("Rule: 1) Both User and Computer can pick sticks between 1 to 4 at a time")
print(" 2) Whosoever picks the last stick will be the looser")
print("==== Lets Begin ======")
playerName = input("Enter Your Name :")
userPick=0
PrintStick(TotalStick)
while win==False:
if humanPlayer==True:
print("You Can Pick stick between 1 to 4")
userPick=0
while userPick<=0 or userPick>4:
userPick = int(input(playerName +": Enter Number of Stick to Pick"))
TotalStick=TotalStick - userPick
humanPlayer=False
PrintStick(TotalStick)
print("*"*60)
input("Press any key...")
else:
computerPick = (5-userPick)
print("Computer Picks : ",computerPick," Sticks ")
TotalStick=TotalStick -computerPick
PrintStick(TotalStick)
if TotalStick==1:
print("## WINNER : COMPUTER ##")
win=True
print("*"*60)
input("Press any key...")
humanPlayer=True
Page : 24
OUTPUT
Page : 26
Date Experiment No:
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin")
Program 1: Program to connect with database and store record of employee
cur = con.cursor()
and display records.
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved
##") elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
Page : 27
OUTPUT
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0
## Bye!! ##
Page : 28
Date Experiment No:
OUTPUT
########################################
EMPLOYEE SEARCHING FORM
########################################
Page : 29
Date Experiment No:
Page : 30
OUTPUT
########################################
EMPLOYEE UPDATION FORM
########################################
Page : 31
Date Experiment No:
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin",
Program 1: Program to connect with database and delete the record of
database="company")
entered
cur employee number.
= con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
OUTPUT
########################################
EMPLOYEE DELETION FORM
########################################
Page : 32
python4csip.co