You are on page 1of 43

PRACTICAL NO:1

QUESTION: Create user defined functions fact() to calculate factorial of a


number and fibonacci() to print Fibonacci series upto N terms using
Python code.
SOLUTION:
PYTHON CODE:
#Function to calculate the factorial
def fact(a):
sum=1
for i in range(1,a+1):
sum=sum*i
print("Factorial of",a,"is ",sum)
#Function to create a fibonacci series
def fibonacci(a):
count=0
x,y=0,1
if a<=0:
print("Please enter a positive number.")
elif a==1:
print("Series is:",x)
else:
print("Series is:")
while count<a:
print(x)
z=x+y
x=y
y=z
count=count+1
#Main program
a=0
while a != 3:
print("Select any option below\n 1. Factorial\n 2. Fibonacci\n 3. Exit")
a=int(input("Enter the option:"))
if a==1:
x=int(input("Enter a number to find its factorial:"))
fact(x)
elif a==2:
y=int(input("Enter a number to print the fibonacci series:"))
fibonacci(y)
elif a==3:
exit()
OUTPUT:
PRACTICAL NO:2
QUESTION: Write a function that takes a number n and then returns a
randomly generated number having exactly n digits (not starting with
zero) e.g., if n is 2 then function can randomly return a number 10-99 but
07,02 etc. are not valid two digit numbers.
SOLUTION:
PYTHON CODE:
import random
#Function to generate random numbers
def generator(n):
start=10**(n-1)
print("Start is:",start)
stop=(10**n)-1
print("Stop is:",stop)
r=random.randint(start,stop)
print("Random number between",start,"and",stop,"is",r)
#Main program
a=int(input("Enter any number:"))
if a<=0:
print("Enter a positive number.")
elif a==1:
print("Enter a number greater than 1.")
else:
generator(a)
OUTPUT:
PRACTICAL NO:3
QUESTION: Write a program that generates a series using a function
which takes first and last values of the series and then generates four
terms that are equidistant e.g., if two numbers are 1 and 7 then function
returns 1 3 5 7.
SOLUTION:
PYTHON CODE:
#Function to create a series
def series(x,y):
d=(y-x)/3 #It divides the difference in 3 equal parts
return [x,int(x+d),int(x+2*d),y]
#Main program
a=int(input("Enter the starting number of the series:"))
b=int(input("Enter the ending number of the series:"))
print(series(a,b))

OUTPUT:
PRACTICAL NO:4
QUESTION: Write a random number generator function that generates
random numbers between 1 and 6 (simulates a dice).
SOLUTION:
PYTHON CODE:
import random
from random import *
a=randint(1,6)
print("The number generated is:",a)

OUTPUT:
PRACTICAL NO:5
QUESTION: Write a menu driven Python program with following
functions:
a. reverse(): To reverse a string.
b. isPalindrome(): To check whether a string is palindrome or not. (call
reverse() function to reverse).
c. search(): To find whether a substring is present in main string or not.
d. statistics(): To print number of upper case letter, lower case letters,
digits, alphabets and words in a string.
e. close(): To close the program.
SOLUTION:
PYTHON CODE:
def reverse():
print()
a=input("Enter a string:")
print("Reverse string:",a[::-1])
def isPalindrome():
print()
b=input("Enter a string:")
if b==b[::-1]:
print(b,"is a Palindrome.")
else:
print(b,"is not a Palindrome.")
def search():
print()
c=input("Enter a string:")
sub=input("Enter a string you want to search for:")
if c.count(sub)>0:
print(sub,"is in",c)
else:
print(sub,"is not in",c)
def statistics():
print()
u=0
l=0
d=0
al=0
w=0
st=input("Enter the string:")
for i in st:
if i.isupper():
u+=1
if i.islower():
l+=1
if i.isalpha():
al+=1
if i.isdigit():
d+=1
print("Number of uppercase:",u)
print("Number of lowercase:",l)
print("Number of digits:",d)
print("Number of alphabets:",al)
print("Number of words:",len(st.split()))

def close():
exit()

#Main Program
o=0
while o != 5:
print(" ")
print("Select the option.")
print("1.)Reverse the string.\n2.)Palindrome\n3.)Search the
substring.\n4.)Statistics\n5.)Close")
o=int(input("Enter the option:"))
if o==1:
reverse()
if o==2:
isPalindrome()
if o==3:
search()
if o==4:
statistics()
if o==5:
close()
OUTPUT:
PRACTICAL NO:6
QUESTION: Write a menu driven Python program with following
functions:
a. add(): Which asks how many students data is to be entered and then
allows user to add data of that many number of students which includes
students name, roll number, marks in 3 subjects. The function should
calculate average of every student marks and then store it in list object.
b. remove(): Which asks for the name of student whose data is to be
removed and then removes that students entire data from the list object.
Take necessary care to remove the data even if user enters the students
name in incorrect case. (Simran should be removed even if user enters
simran or SIMRAN etc.)
c. display(): Which displays all the students data.
d. close(): To close the program.
The program should run continuously till the time use doesn’t selects exit
option.
SOLUTION:
PYTHON CODE:
student_list=[]
def add():
n=int(input("Please enter number of students:"))
for i in range(1,n+1):
name=input("Enter name:")
roll=int(input("Enter roll number:"))
p=float(input("Enter marks in Physics:"))
c=float(input("Enter marks in Chemistry:"))
m=float(input("Enter marks in Mathematics:"))
avg=(p+c+m)/3
student_list.append([name,roll,p,c,m,avg])

def remove():
r=input("Enter name of the student to remove:")
found=False
for i in student_list:
if i[0].lower()==r.lower():
student_list.remove(i)
found=True
if found==False:
print("No such student exists.")
else:
print("Record removed successfully.")

def display():
print("STUDENT DATA")
print("NAME ROLLNO PHY CHEM MATH AVG")
for i in range(len(student_list)):
print(student_list[i])

#Main Program
choice=0
while choice !=4:
print("Student data record system")
print("1. Add records\n2. Remove records\n3. Display records\n4.
Close")
choice=int(input("Enter the choice:"))
if choice==1:
add()
if choice==2:
remove()
if choice==3:
display()
if choice==4:
exit()

OUTPUT:
PRACTICAL NO:7
QUESTION: Create a text file “story.txt” in your folder using notepad with
following content to do the following:
a. Total number of words.
b. Total number of word Jack.
c. Total number of vowels.
d. Total number of spaces.
e. Total number of uppercase characters.
f. Total number of lowercase characters.

SOLUTION:
PYTHON CODE:
# a.Total number of words
def a():
with open("story.txt",'r') as obj1:
f1=obj1.read()
lst1=f1.split()
print("Number of words are:",len(lst1))

# b.Total number of word Jack.


def b():
with open("story.txt",'r') as obj2:
f2=obj2.read()
lst2=f2.split()
c=0
for i in lst2:
if i=='Jack':
c+=1
print("Number of word Jack are:",c)
# c.Total number of vowels
def c():
with open("story.txt",'r') as obj3:
f3=obj3.read()
v=0
for i in f3:
if i in ['a','e','i','o','u','A','E','I','O','U']:
v+=1
print("Number of vowels are:",v)

# d.Total number of spaces


def d():
with open("story.txt",'r') as obj4:
f4=obj4.read()
s=0
for i in f4:
if i ==' ':
s+=1
print("Number of spaces are:",s)

# e.Total number of uppercase characters


def e():
with open("story.txt",'r') as obj5:
f5=obj5.read()
u=0
for i in f5:
if i.isupper()==True:
u+=1
print("Number of uppercase characters are:",u)

# f.Total number of lowercase characters


def f():
with open("story.txt",'r') as obj6:
f6=obj6.read()
l=0
for i in f6:
if i.islower():
l+=1
print("Number of lowercase characters are:",l)

a()
b()
c()
d()
e()
f()

OUTPUT:
PRACTICAL NO:8
QUESTION: A file sports.txt contains information in following format:
Event ~ Participant Write a function that would read contents from file
sports.txt and creates a file named Atheletic.txt copying only those
records from sports.txt where the event name is “Atheletics”.

SOLUTION:
PYTHON CODE:
file1 = open("sports.txt","r")
file2 = open("Atheletics.txt","w")
lst = file1.readlines()
for i in lst :
a=i.split()
if a[2] == "atheletics" or a[2] == "Atheletics" :
file2.write(i)

file1.close()
file2.close()

OUTPUT:
PRACTICAL NO:9
QUESTION: Write a Python program to search for a given string in the file
and find how many times it occurs in the file.

SOLUTION:
PYTHON CODE:
obj=open("story.txt",'r')
c=0
f=obj.read()
lst=f.split()
word=input("Enter the word you are searching for:")
for i in lst:
if i==word:
c+=1
if c>0:
print(word,"is",c,"times in the text.")
else:
print(word,"is not in the text.")
obj.close()

OUTPUT:
PRACTICAL NO:10
QUESTION: Write a function displaywords() in python to read lines from a
text file story.txt, and display those words, which are less than 4
characters.

SOLUTION:
PYTHON CODE:
def displaywords():
obj=open("story.txt",'r')
f=obj.read()
lst=f.split()
for i in lst:
if len(i)<4:
print(i)
obj.close()
displaywords()
OUTPUT:
PRACTICAL NO:11
QUESTION: Write a function in python to count and display the number
of lines starting with alphabet ‘A’ present in a text file lines.txt. e.g., the
file lines.txt contains the following lines:

SOLUTION:
PYTHON CODE:
obj=open("lines.txt",'r')
c=0
f=obj.readlines()
for i in f:
if i[0][0]=='A':
c+=1
print("The total number of lines starting with 'A' are:",c)
obj.close()

OUTPUT:
PRACTICAL NO:12
QUESTION: Write a program which deals with the text file data.txt and
perform the following operations:
a. Read the text file line by line and display each word separated by a #.
b. Remove all the lines that contain the character ‘a’ from the file and
write it to another file named data1.txt.

SOLUTION:
PYTHON CODE:
# a. part
obj=open("data.txt",'r')
l=obj.readlines()
for i in l:
w=i.split()
for a in w:
print(a+'#',end='')
obj.close()

# b. part
a=open("data.txt","r")
b=a.readlines()
a.close()
c=list()
for i in b:
if "a" or "A" in i:
c.append(i)
for i in c:
try:
b.remove(i)
except:
continue
a=open("data1.txt","w")
a.writelines(b)
a.close()

OUTPUT:
PRACTICAL NO:13
QUESTION: Write a menu driven python program with following
functions:
a. Create a binary file student.dat containing each students roll number,
name and marks.
b. Append one record in student.dat binary file.
c. Search for a given roll number entered by user. If not found display
appropriate error message.
d. Modify the marks of student as per entered roll number by the user. If
not found display appropriate error message.
e. Display the contents of the file.
f. Exit
SOLUTION:
PYTHON CODE:
#menu drivem program
import pickle
import sys
print("Which operation do you wish to perform?\n1. Create a binary file
student.dat containing each students roll number, name and marks\n2.
Append one record in student.dat binary file\n3. Search for a given roll
number\n4. Modify the marks of student as per entered roll number\n5.
Display the contents of the file\n6. Exit")
choice=int(input("Enter your choice:"))
while True:
if choice==1:
obj1=open('student.dat','wb')
stu={}
ans='y'
while ans.lower()=='y':
name=input('Enter name of student:')
rollno=int(input('Enter roll number of student:'))
marks=int(input('Enter marks of student:'))
stu['Name']=name
stu['Roll no']=rollno
stu['Marks']=marks

pickle.dump(stu,obj1)
ans=input('Do you wish to enter more records? Enter y or
n:')
obj1.close()
elif choice==2:
obj2=open('student.dat','ab')
stu={}
name=input('Enter name of student:')
rollno=int(input('Enter roll number of student:'))
marks=int(input('Enter marks of student:'))
stu['Name']=name
stu['Roll no']=rollno
stu['Marks']=marks
pickle.dump(stu,obj2)
print("Record added")
obj2.close()
elif choice==3:
obj3=open('student.dat','rb')
rollno=int(input('Enter the roll number you want to search for:'))
found=False
try:
while True:
a=pickle.load(obj3)
if a['Roll no']==rollno:
print("Record found")
print(a)
found=True
except:
if found==False:
print('Record not found for roll number',rollno)
obj3.close()
elif choice==4:
obj4=open('student.dat','r+b')
rollno=int(input('Enter the roll number for whom you want to
modify marks:'))
found=False
try:
while True:
pointer=obj4.tell()
a=pickle.load(obj4)
if a['Roll no']==rollno:
marks=int(input("Enter the new marks:"))
a['Marks']=marks
obj4.seek(pointer)
pickle.dump(a,obj4)
print("Record updated")
found=True
except:
if found==False:
print('Record not found for roll number',rollno)
obj4.close()
elif choice==5:
obj5=open('student.dat','rb')
try:
while True:
print(pickle.load(obj5))
except:
obj5.close()
elif choice==6:
print("Exiting...")
sys.exit()
else:
print("Enter 1,2,3,4,5 or 6 only!\nEnter again")

choice=int(input("Enter your choice:"))


OUTPUT:
PRACTICAL NO:14
QUESTION: Write a menu driven python program with following
functions:
a. Create a csv file to store details for multiple items (code, name, price)
entered by the user. Use tab as the delimiter character. (The user will
enter how many items details he/she would like to enter)
b. Read the data from the csv file and display it.
c. Close the application.
SOLUTION:
PYTHON CODE:
import csv
def writedata():
a=open("items.csv",'w',newline='')
writer_obj=csv.writer(a,delimiter='\t')
writer_obj.writerow(["Code","Name","Price"])
n=int(input("Enter the number of items:"))
for i in range(n):
c=int(input("Enter code:"))
n=input("Enter name:")
p=int(input("Enter price:"))
writer_obj.writerow([c,n,p])
a.close()

def readdata():
a=open("items.csv",'r')
reader_obj=csv.reader(a,delimiter='\t')
for i in reader_obj:
print(i)
a.close()
choice=0
while choice!=3:
print("Select any option:")
print("1.Write")
print("2.Read")
print("3.Close")
choice=int(input("Enter choice:"))
if choice==1:
writedata()
if choice==2:
readdata()
if choice==3:
exit()
OUTPUT:
PRACTICAL NO:15
QUESTION: Write a menu driven python program with following
functions:
a. Create a csv file to store user-id and password for different users. (The
user will enter how many records he/she would like to enter)
b. Read the data from the csv file and display it.
c. Search for the password of a user depending on his/her user-id. If the
user-id does not exist then display appropriate error message.
d. Close the application.
SOLUTION:
PYTHON CODE:
import csv
def record():
a=open("credentials.csv",'w',newline='')
writer_obj=csv.writer(a)
writer_obj.writerow(["ID","Password"])
n=int(input("Enter the number of users:"))
for i in range(n):
d=input("Enter user ID:")
p=int(input("Enter password:"))
writer_obj.writerow([d,p])
a.close()

def readdata():
a=open("credentials.csv",'r')
reader_obj=csv.reader(a)
for i in reader_obj:
print(i)
a.close()

def search():
a=open("credentials.csv",'r')
reader_obj=csv.reader(a)
uid=input("Enter the user ID:")
for i in reader_obj:
if uid==i[0]:
print(i)
a.close()

choice=0
while choice!=4:
print("Select any option:")
print("1.Write")
print("2.Read")
print("3.Search")
print("4.Close")
choice=int(input("Enter choice:"))
if choice==1:
record()
if choice==2:
readdata()
if choice==3:
search()
if choice==4:
exit()

OUTPUT:

You might also like