Computer Science – Practical File Programs
GRADE: XII – MAT / BIO / COMM – CS
Ex. No: 1
FACTORIAL OF A NUMBER USING FUNCTION
Aim
To write a Python program to calculate Factorial of a given Number using function.
Program Algorithm:
Step1: Start.
Step2: Get input number from the user.
Step3: Call user defined function by passing the number as an argument.
Step4: Calculate factorial of the passed argument and return the value.
Step5: Print the result.
Step6: Stop.
Program Code:
def factorial (n):
fact = 1
for i in range(1,n+1):
fact = fact*i
return fact
x = int(input("Enter number: "))
result = factorial (x)
print("Factorial of " ,x, " is :", result)
Output:
Enter number: 5
Factorial of 5 is: 120
Conclusion:
The above program was successfully1 executed.
Ex. No: 2
GENERATE A FIBONACCI SERIES
Aim:
To write a Python program using function to compute the nth Fibonacci number.
Program Algorithm:
Step1: Start.
Step2: Get input number from the user.
Step3: Call user defined function by passing the number as an argument.
Step4: To generate Fibonacci series of the passed argument by the function
fibonacci ( ) and display the series.
Step5: Print the result.
Step6: Stop.
Program Code:
def fibonacci(n):
a=0
b=1
if n<0:
print ("Incorrect Input:")
elif n==0:
print(a)
elif n==1:
print(a,b)
else:
print(a,b,end=" ")
for i in range(n-2):
c=a+b
print(c,end=" ")
a=b
b=c 2
print("*Printing Fibonacci Series*")
x=int(input("How many numbers you want to display : "))
print("The Fibonacci Series is: ")
fibonacci(x)
Output:
*Printing Fibonacci Series*
How many numbers you want to display: 10
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34
Conclusion:
The above program was successfully executed.
3
Ex. No: 3
COUNT UPPERCASE AND LOWERCASE LETTER
Aim:
To write a Python program to count and display the upper case and lower case letters
in the in a string which is passed as an argument to the function.
Program Algorithm:
Step1: Start.
Step2: Read string as input from the user.
Step3: Call the user-defined function by passing string as an argument.
Step4: Find the number of uppercase letters and lowercase letters using
Built- in- function in Python and return the lowercase and uppercase
Counting as a value.
Step 5: Print the result.
Step 6: Stop.
Program Code:
def string_test(string):
ucount=0
lcount=0
for i in string:
if i.isupper():
ucount+=1
if i.islower():
lcount+=1
return ucount, lcount
S=input("Enter any string:")
print("Original string is = ", S)
uc,lc=string_test(S)
print("No. of UCASE = ",uc)
print("No. of LCASE = ",lc)
4
Output:
Enter any string: Welcome To PYTHON
Original string is = Welcome To PYTHON
No. of Uppercase = 8
No. of Lowercase = 7
Conclusion:
The above program was successfully executed.
5
Ex. No: 4
CHECK PRIME NUMBER
Aim:
To write a Python program to check whether the given number is Prime or Not a
Prime by using function.
Program Algorithm:
Step1: Start.
Step2: Read value from the user as Input.
Step3: Call user-defined function by passing the number as an argument.
Step4: To check the pass argument whether number is prime or not and return it.
Step5: Print the result.
Step6: Stop.
Program Code:
def prime_test(n):
c=0
for i in range(1,n+1):
if n%i==0:
c=c+1
return c
N=int(input("Enter a Value = "))
c=prime_test(N)
if c==2:
print(N , "is a Prime Number")
else:
print(N, "is not a Prime Number")
6
Output: 1
Enter a Value = 19
19 is a Prime Number
Output: 2
Enter a Value = 15
15 is a not Prime Number
Conclusion:
The above program was successfully executed.
7
Ex. No: 5
PROGRAM TO COUNT ANY WORD IN STRING
Aim:
To write a Python program to find the occurrence of any word in a string which is
passed as argument to function.
Program Algorithm:
Step 1 : Start
Step 2 : Read input string from the user.
Step 3 : Read the word to be searched in the above string.
Step 4 : Call user defined function by passing string and the word as an argument.
Step 5 : Split the passed string and count number of words.
Step 6 : Return the count value.
Step 7 : Print the result.
Step 8 : Stop
Program Code:
def count_word(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
str1 = input("Enter any sentence :")
word = input("Enter word to search in sentence :")
count = count_word(str1,word)
if count==0:
print("Sorry! ",word," not present ")
else:
print(word," occurs ",count," times")
8
Output: 1
Enter any sentence: Raju likes fruits and Ravi likes sweets
Enter word to search in sentence: likes
likes occurs 2 times
Output: 2
Enter any sentence: Raju likes fruits and Ravi likes sweets
Enter word to search in sentence: Ice cream
Sorry! Ice cream not present
Conclusion:
The above program was successfully executed.
9
Ex. No: 6
PROGRAM TO SIMULATE THE DICE
Aim:
To write a Python program to simulate the dice using random module.
Program Algorithm:
Step 1 : Start.
Step 2 : Repeatedly generate random number using randint(1,6) and display the
number with equal time interval.
Step 3 : Press CTRL+C to stop generating random number.
Step 4 : Print the number.
Step 5 : Stop.
Program Code:
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):
n = random.randint(1,6)
print(n)
time.sleep(0.5)
except KeyboardInterrupt:
print("\nYour Number is :",n)
ans=input("Play More? (Y) :")
10
if ans.lower()!='y':
play='n'
break
Output:
Press CTRL+C to stop the dice!!!
2
2
6
1
5
3
6
5
3
5
2
3
3
5
5
Your Number is : 5
Play More? (Y) :n
>>>
Conclusion:
The above program was successfully executed.
11
EX. No. 7
PROGRAM TO COUNT THE NUMBER OF LINES AND
WORDS IN A TEXT FILE
Aim:
To write a Python program to count the number of lines and words in a text file.
Program Algorithm:
Step 1 : Start.
Step 2 : Create text file using notepad and save it.
Step 3 : Open the created text file in read mode.
Step 4 : Apply readlines() to read all the lines and count the number of lines.
Step 5 : Now set the file pointer to the beginning of file and read the entire file and
count the number of words using split().
Step 6 : Print the result
Step 7 : Stop.
Program Code:
myfile=open("F:\\TextFile\\Poem.txt","r")
Lines=myfile.readlines()
NOL=len(Lines)
myfile.seek(0)
words=myfile.read()
NOW=words.split()
print("Number of Lines in a text file:",NOL)
print("Number of Words in a text file:",len(NOW))
12
Output:
Number of Lines in a text file: 4
Number of Words in a text file: 23
Conclusion:
The above program was successfully executed.
13
EX. No. 8
PROGRAM TO READ A LINE AND WORD SEPARATED BY #
Aim:
To write a Python program to read a text file line by line and display word separated
by a #.
Program Algorithm:
Step 1 : Start.
Step 2 : Create text file using notepad and save it.
Step 3 : Open the created text file in read mode.
Step 4 : Apply readlines() to read all the lines and count the number of lines.
Step 5 : Now set the file pointer to the beginning of file and read the entire file and
count the number of words using split().
Step 6 : Then each word separated by #
Step 7: Print the Result.
Step 7 : Stop.
Program Code :
file=open("AI.TXT","r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close() 14
Output:
Welcome#to#Python#Programming#language#
Conclusion:
The above program was successfully executed.
15
EX. No. 9
PROGRAM TO COUNT VOWELS AND
CONSONANTS/UPPERCASE/LOWER CASE LETTER IN FILE
Aim:
To write a program to Read a Text file and display the number of vowels/
consonants/ uppercase/ lowercase characters in the file.
Program Algorithm:
Step 1 : Start.
Step 2 : Create text file using notepad and save it.
Step 3 : Open the created text file in read mode.
Step 4 : Apply read to read all the lines and count the number of lines.
Step 5 : To check and count the vowels, consonants, upper and lowercase letter
in a file by using methods,
Step 7: Print the Result.
Step 7 : Stop.
Program Code:
file=open("AI.TXT","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if ch.islower():
lower_case_letters+=1
16
elif ch.isupper():
upper_case_letters+=1
ch=ch.lower()
if ch in ['a','e','i','o','u']:
vowels+=1
elif ch in
['b','c','d','f','g','h','j','k','l','m','n','p','q','r',
's','t','v','w','x','y','z'):
consonants+=1
file.close()
print("Vowels are :",vowels)
print("Consonants :",consonants)
print("Lower_case_letters :",lower_case_letters)
print("Upper_case_letters :",upper_case_letters)
Output:
Vowels are : 12
Consonants : 22
Lower_case_letters : 31
Upper_case_letters : 3
Conclusion:
The above program was successfully executed.
17
EX. No. 10
PROGRAM TO COPY THE CONTENT OF TEXT FILE
Aim:
To write a Python program to copy the content of text file which are starting with ‘I’
to another file.
Program Algorithm:
Step 1 : Start.
Step 2 : Create Source text file using notepad and save it.
Step 3 : Open source file in read mode and target file in write mode.
Step 4 : Read each line from the source text file and check whether it is starting
With ‘I’.
Step 5 : Write the line into target file.
Step 6 : Print the content of target file.
Step 7 : Stop.
Program Code :
f=open("poem.txt",'r')
f1=open("Copypoem.txt","w")
while True:
txt=f.readline()
if len(txt)==0:
break
if txt[0]=='I':
f1.write(txt)
print("File Copied!")
print("Contents of new file:")
f.close()
18
with open("Copypoem.txt","r") as f1:
print(f1.read())
Output:
File Copied!
Contents of new file:
I love my country
I am proud to be Indian
Conclusion:
The above program was successfully executed.
19
EX. No. 11
PROGRAM TO CREATE A BINARY FILE
Aim:
To write a Python program to create binary file and store the details of a
student.
Program Algorithm:
Step 1 : Start.
Step 2 : Import pickle module and open binary file in write mode.
Step 3 : Get student details from the user and store it in dictionary variable.
Step 4 : Write the record into the file using dump().
Step 5 : Open the same file in read mode and read its content using load()
Step 6 : Display the content of file.
Step 7 : Stop.
Program Code:
import pickle
stu={}
myfile=open('student.dat','wb')
choice='y'
while choice=='y':
Rno=int(input("Enter Roll Number:"))
Name=input("Enter Name:")
Class=int(input("Enter Class(11/12):"))
Total=int(input("Enter Total Marks:"))
stu['RollNo']=Rno
stu['Name']=Name
stu['Class']=Class
stu['Marks']=Total
20
pickle.dump(stu,myfile)
choice=input("Do you want to add more
records?(y/n)...")
myfile.close()
stu={}
fin=open('student.dat','rb')
try:
print("File Contents:")
while True:
stu=pickle.load(fin)
print(stu)
except EOFError:
fin.close()
Output:
Enter Roll Number:101
Enter Name:Rajiv
Enter Class(11/12):12
Enter Total Marks:450
Do you want to add more records?(y/n)...y
Enter Roll Number:102
Enter Name:Sanjay
Enter Class(11/12):12
Enter Total Marks:400
21
Do you want to add more records?(y/n)...n
File Contents:
{'RollNo': 101, 'Name': 'Rajiv', 'Class': 12, 'Marks': 450}
{'RollNo': 102, 'Name': 'Sanjay', 'Class': 12, 'Marks': 400}
Conclusion:
The above program was successfully executed.
22
Ex. No: 12
PROGRAM TO UPDATE THE CONENT OF
BINARY FILE
Aim:
To write a Python program to update the content of binary file.
Program Algorithm:
Step 1 : Start.
Step 2 : Import pickle module and open binary file in read/write mode.
Step 3 : Get the roll number of a student to identify the record.
Step 4 : Read the file using load() and identify the record to be updated.
Step 5 : Update the mark of a student and write the updated record back into the file
using dump().
Step 6 : Now display the content of updated file.
Step 7 : Stop.
Program Coding:
import pickle
stu={}
found=False
myfile=open('student.dat','rb+')
n=int(input("Enter Roll number of a student to update his
mark:"))
try:
while True:
pos=myfile.tell()
stu=pickle.load(myfile)
if stu['RollNo']==n:
23
stu['Marks']+=10
myfile.seek(pos)
pickle.dump(stu,myfile)
found=True
except EOFError:
if found==False:
print("No matching record found!")
else:
print("Record Successfully Updated!")
try:
myfile.seek(0)
print("File Content after updation:")
while True:
stu=pickle.load(myfile)
print(stu)
except EOFError:
myfile.close()
myfile.close()
Output 1:
Enter Roll number of a student to update his mark:101
Record Successfully Updated!
File Content after updation:
{'RollNo': 101, 'Name': 'Rajiv', 'Class': 12, 'Marks': 460}
{'RollNo': 102, 'Name': 'Sanjay', 'Class': 12, 'Marks': 400}
24
Output 2:
Enter Roll number of a student to update his mark:103
No matching record found!
Conclusion:
The above program was successfully executed.
25
Ex. No: 13
PROGRAM TO CREATE CSV FILE
Aim:
To write a Python program to create CSV file to store information about some
products.
Program Algorithm:
Step 1 : Start.
Step 2 : Import csv module and open file in write mode.
Step 3 : Create writer object and write the product details into the file using
writerow().
Step 4 : Open the above created file in read mode using with statement.
Step 5 : Read the file using reader object.
Step 6 : Display the contents of file.
Step 7 : Stop.
Program Code:
import csv
myfile=open('Product.csv','w',newline='')
prod_writer=csv.writer(myfile)
prod_writer.writerow(['CODE','NAME','PRICE'])
for i in range(2):
print("Product", i+1)
code=int(input("Enter Product code:"))
name=input("Enter Product Name:")
price=float(input("Enter Price:"))
prod=[code,name,price]
prod_writer.writerow(prod)
26
print("File Contents:")
print(“------------------”)
myfile.close()
with open("Product.csv","r",newline='\n') as fh:
prod_reader=csv.reader(fh)
for rec in prod_reader:
print(rec)
Output:
Product 1
Enter Product code:104
Enter Product Name: Pen
Enter Price:200
Product 2
Enter Product code:405
Enter Product Name: Marker
Enter Price:50
File created successfully!
File Contents:
------------------
['CODE', 'NAME', 'PRICE']
['104', 'Pen', '200.0']
['405', 'Marker', '50.0']
Conclusion:
The above program was successfully executed.
27
Ex. No: 14
PROGRAM TO DISPLAY THE EMPLOYEE
RECORDS
Aim:
To write a python program to define the following function.
a) DISPEMP( )
Using this function to read the content of the emp file and
display only those records where salary is above 10000.
b) SNAMES( )
Using this function to read the content of the emp file and
display the employee record whose name begins with from ‘A’ .
Program Algorithm
Step 1 : Start.
Step 2 : Import csv module and open file in write mode.
Step 3 : Create reader object and read the Employee details into the file using
reader ( )
Step 4 : Open the above created file in read mode using with statement.
Step 5 : Read the file using reader object.
Step 6 : Display the contents of file.
Step 7 : Stop.
Program Code:
import csv
def DISPEMP( ):
with open("emp.csv") as f1:
emp=csv.reader(f1)
print("Employee Details >10000")
print("**************************")
for row in emp:
if int(row[3])>10000:
print(row[0],row[1],row[2],row[3])
28
print("Records are Successfully Displayed...")
print("*************************************")
def SNAMES( ):
with open("emp.csv") as f2:
emp=csv.reader(f2)
count=0
print("Employee Details whose starts with A")
print("**********************************")
for row in emp:
if row[1][0]=='A':
count=count+1
print(row[0],row[1],row[2],row[3])
print("The No. Employee Name starts
with 'A' is = ",count)
DISPEMP()
SNAMES()
Output:
Employee Details >10000
**********************
101 Raju Manager 15000
104 Sasi Manager 12000
105 Arjun Accountant 11000
Records are Successfully Displayed...
*************************************
29
Employee Details whose starts with A
****************************************
103 Abisek Accountant 7000
105 Arjun Accountant 11000
The No. Employee Name starts with 'A' is = 2
Conclusion:
The above program was successfully executed.
30
Ex. No: 15
PROGRAM TO SEARCH A RECORD IN CSV FILE
Aim:
To write a python program to get a player name and their score.
Program Algorithm:
Step 1 : Start.
Step 2 : Import csv module and open file in write mode.
Step 3 : Create writer object and write the product details into the file using
writerow().
Step 4 : Open the above created file in read mode using with statement.
Step 5 : Read the file using reader object.
Step 6 : Display the contents of file.
Step 7 : Stop.
Program Code:
import csv
with open('E:\\player.csv','w') as f:
w = csv.writer(f)
n=1
while (n<=3):
name = input("Player Name?:" )
score = int(input("Score: "))
w.writerow([name,score])
n+=1
print("\nPlayer File created")
f.close()
31
print("\n--------------OUTPUT----------------")
searchname=input("Enter the name to be searched : ")
f=open('E:\\player.csv','r')
reader =csv.reader(f)
lst=[]
for row in reader:
lst.append(row)
q=0
for row in lst:
if searchname in row:
print(row)
q+=1
if(q==0):
print("\nPlayer not found")
f.close()
Output:
Player Name?:A
Score: 34
Player Name?:B
Score: 67
Player Name?:C
Score: 78
32
Player File created
--------------OUTPUT----------------
Enter the name to be searched: B
['B', '67']
Conclusion:
The above program was successfully executed.
33