0% found this document useful (0 votes)
28 views26 pages

Class 12 Python Programs For Practical File

Uploaded by

ak96541988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views26 pages

Class 12 Python Programs For Practical File

Uploaded by

ak96541988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

PYTHON PROGRAMS FOR PRACTICAL

FILE
1.Read a text file line by line and replace the space character
between words with # symbol.
Input:
with open('newmain.txt', 'w+') as f:

f.writelines(['This is a test file.\n',


'It contains some text.\n',
'We will replace spaces with underscores.\n',
'How are you?\n'])
with open('main.txt', 'r') as f:

rep = f.read()
rep = rep.replace(' ', '#')
print(rep)
with open('newmain.txt', 'w+') as f:
f.write(rep)

f.close()

Output:
2. Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Input:
vowel= 0
consonant= 0
uppercase= 0

lowercase= 0
with open("main.txt", "r") as file:
a = file.read()
for char in a:
if char.isalpha():
if char.lower() in 'aeiou':
vowel += 1
else:
consonant += 1
if char.isupper():

uppercase += 1
elif char.islower():
lowercase += 1
print('vowel',vowel)
print('consonant',consonant)

print('uppercase',uppercase)
print('lowercase',lowercase)

Output:
3. Remove all the lines that contain the word 'are' from a file and
write those lines to another file.
Input:
with open('main.txt','r')as p:

a = ''
f = p.readlines()
for line in f:
if 'are' in line:
a += line

with open('remove.txt','w')as f:
f.write(a)

output:
4. Write a program in Python to get student details (Rollno,
Name and Marks) for multiple students from the user and create
a CSV file by writing all the student details in one go. Also read
and display the data of CSV file.
Input:
import csv

f = open('Student.csv', 'w')

stuwriter = csv.writer(f)

stuwriter.writerow(['Name', 'Roll No', 'Marks'])

while True:

name = input('Enter student name: ')

roll_no = input('Enter roll number: ')

marks = input('Enter marks: ')

stuwriter.writerow([name, roll_no, marks])

cont = input('Do you want to add another student? (y/n): ')

if cont.lower() != 'y':

break

f.close()

fc = open('Student.csv', 'r')

print(csv.reader(fc))

Output
5. Create a binary file with roll number, name and marks. Input
a roll number and update the marks.
Input:
import pickle

students = []

with open('students.dat', 'wb') as f:

while True:

student = {}

student['name'] = input('Enter student name: ')

student['roll_no'] = input('Enter roll number: ')

student['marks'] = input('Enter marks: ')

students.append(student)

more = input('Do you want to add another student? (y/n): ')

if more.lower() != 'y':

break

pickle.dump(students, f)

f.close()

with open('students.dat', 'rb') as f:

try:

while True:

students = pickle.load(f)

for student in students:

print(student)

update = input('Do you want to update the student details? (y/n): ')

if update.lower() != 'y':

break

updated_roll_no = input('Enter the roll number to update marks: ')

for student in students:

if student['roll_no'] == updated_roll_no:

update_marks = input('Enter marks for update: ')

student['marks'] = update_marks

break

except EOFError:
with open('students_updated.dat', 'wb') as f:

pickle.dump(students, f)

for a in students:

print(a)

pass

Output:
6. Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
Input:
for _ in range(1,7):
def Dice_roll():
import random
return random.randint(1,6)
print(f'Dice number:{Dice_roll()}')
Output:
7. Write a Python program to implement a stack using list.
Input:
stack = []
def push(data):
print("Pushed:", data)
return stack.append(data)
def pop():
while True:
if len(stack) !=0:
print("Popped element:",stack.pop())
if len(stack) == 0:
print("stack is underflow")
print("Stack is empty")
push(10)
push(20)
push(30)
print("Stack after pushing elements:", stack)
pop()

Output:
8. Create a CSV file by entering user-id and password, read and
search the password for given userid.
Input:
import csv

with open('Uid and Pwd.csv', 'w', newline='') as f:

write = csv.writer(f)

write.writerow(['UID', 'Password'])

while True:

uid = input('Enter your UID: ')

pwd = input('Enter your Password: ')

write.writerow([uid, pwd])

cont = input('Do you want to add another user? (y/n): ')

if cont.lower() != 'y':

break

with open('Uid and Pwd.csv', 'r', newline='') as f:

read = csv.reader(f)

search = input('Enter the UID to search password: ')

for row in read:

if row[0] == search:

print(f'Password is:{row[1]}')

break

else:

print('UID not found')

Output:
9. To secure your account, whether it be an email,online
bank account or any other account, it is important that we
use authentication. Use your programming expertise to
create a program using user defined function named login
that accepts userid and password as parameters
(login(uid,pwd)) that displays a message “account blocked” in
case of three wrong attempts. The login is successful if the
user enters user ID as "ADMIN" and password as "St0rE@1".
On successful login, display a message “login successful”.
Input:
def login(u,p):

for i in range(1,3):

if u =='admin' and p=='St0rE@1':

print('<<< login successfully >>>')

return

else:

print('<<< try again >>>')

u= input('user id: ')

p= input('password:')

print('<<< Too many attemt to login so, your account is blocked >>>')

u= input('user id: ')

p= input('password:')

login(u,p)

Output:
10. Take a look at the series below: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55…
To form the pattern, start by writing 1 and 1. Add them together
to get 2. Add the last two numbers: 1+2 = 3.Continue adding the
previous two numbers to find the next number in the series.
These numbers make up the famed Fibonacci sequence: previous
two numbers are added to get the immediate new number.
Input:
a=1

b=1

def fibonacci(n):

global a, b

fib_series = [a, b]

for _ in range(2, n):

a, b = b, a + b

fib_series.append(b)

return fib_series

n = int(input("Enter the number of terms you want: "))

print(f'Fibonacci series up to 10 terms: {fibonacci(n)}')

Output:
11. Create a menu driven program using user defined functions to
implement a calculator that performsthe following:
a) Basic arithmetic operations(+,-,*,/)
b) log10(x),sin(x),cos(x) .
Input:
import math

def add(x, y):

return x + y

def subtract(x, y):

return x - y

def multiply(x, y):

return x * y

def divide(x, y):

if y == 0:

return "Error: Division by zero is not allowed"

return x / y

def log10(x):

if x <= 0:

return "Error: Logarithm is not defined for non-positive numbers"

return math.log10(x)

def sin(x):

return math.sin(math.radians(x))

def cos(x):

return math.cos(math.radians(x))

def calculator():

while True:

print("Calculator Menu:")

print("1. Basic Arithmetic Operations")

print("2. Trigonometric Functions")

print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == "1":

print("Basic Arithmetic Operations:")


print("1. Addition")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

op_choice = input("Enter your choice (1/2/3/4): ")

if op_choice == "1":

x = float(input("Enter the first number: "))

y = float(input("Enter the second number: "))

print("Result:", add(x, y))

elif op_choice == "2":

x = float(input("Enter the first number: "))

y = float(input("Enter the second number: "))

print("Result:", subtract(x, y))

elif op_choice == "3":

x = float(input("Enter the first number: "))

y = float(input("Enter the second number: "))

print("Result:", multiply(x, y))

elif op_choice == "4":

x = float(input("Enter the first number: "))

y = float(input("Enter the second number: "))

print("Result:", divide(x, y))

else:

print("Invalid choice. Please try again.")

elif choice == "2":

print("Trigonometric Functions:")

print("1. Log10(x)")

print("2. Sin(x)")

print("3. Cos(x)")

func_choice = input("Enter your choice (1/2/3): ")

if func_choice == "1":

x = float(input("Enter the number: "))

print("Result:", log10(x))

elif func_choice == "2":

x = float(input("Enter the angle in degrees: "))


print("Result:", sin(x))

elif func_choice == "3":

x = float(input("Enter the angle in degrees: "))

print("Result:", cos(x))

else:

print("Invalid choice. Please try again.")

elif choice == "3":

print("Exiting the calculator. Goodbye!")

break

else:

print("Invalid choice. Please try again.")

calculator()

Output:
12.Write a program that creates a GK quiz consisting of any five
questions of your choice. The questions should be displayed
randomly. Create a user defined function score() to calculate the
score of the quiz and another user defined function remark
(scorevalue) that accepts the final score to display remarks as
follows:
Input:
questions = {
"1. Who is the father of computer?": {

"options": ["A. Charles Babbage", "B. Alan Turing","C. Steve Jobs",


"D. Bill Gates"],
"answer": "A"},
"2. Full form of IAS?": {
"options": ["A. Indian Armed Services", "B. Indian Academic Services",

"C. Indian Airport Services","D. Indian Administrative Services"],


"answer": "D"},
"3. Which of the following is not a programming language?": {
"options": ["A. C","B. C++","C. Java++","D. Python"],
"answer": "None"},

"4. Who is the current president of India?": {


"options": ["A. Narendra Modi", "B. Droupadi Murmu", "C. Rahul Gandhi",
"D. Ratan Tata"],
"answer": "B"},
"5. Full form of IPS": {

"options": ["A. Indian Police Services","B. Indian Political Services",

"C. Indian Power Services","D. Indian Poll Services"],


"answer": "A"}}
def quiz_game():
score = 0

for question, data in questions.items():


print(question)
for option in data["options"]:
print(option)

while True:
user_answer = input("Your answer (A, B, C, D): ").upper()
if user_answer in ["A", "B", "C", "D"]:
break
print("Invalid input. Please try again.")

if data["answer"] == "None":
if user_answer != "D":
print("Correct")
score += 1
else:

print("Incorrect")
elif user_answer == data["answer"]:
print("Correct")
score += 1
else:

print("Incorrect")
print()
print("Your final score is:", score)
if score == len(questions):
print("Outstanding")

elif score == len(questions) - 1:


print("Excellent")
elif score == len(questions) - 2:
print("Good")
elif score == len(questions) - 3:

print("Read more to score more")


elif score == len(questions) - 4:

print("Need to take interest")


else:
print("General Knowledge will always help you. Take it Seriously")
play_game = input("Do you want to play the game? (y/n): ")

if play_game.lower() == "y":
quiz_game()

Output:
13.A school has created a dictionary containing top players and their runs as
key value pairs of cricket team. Write a program, with separate user defined
function to perform the following operations: a) Push the name of the
players(eys) of the dictionary into a stack, where the corresponding runs
(value) is greater than 49. b) Pop and display the content of the stack. For
example, If dictionary has the following values:
Data={‘Rohan’:40,’Rihaan’:55,’Tejas’:80,’Ajay’:90} The output should be:
Ajay
Tejas
Rihaan
Input:
dict ={'Rohan':40,'Rihaan':55,'Tejas':80,'Ajay':90}

player =[]

def push():

for i in dict:

if dict[i] >=49:

player.append(i)

push()

def pop():

while True:

if len(player)!=0:

print(f'Players are scored more than 49 runs: {player.pop()}')

pop()

Output:
14.A binary file Book.dat has structure [BookNo, BookName, Author] a) Write
a user defined function FileData() to input data for a record and add to
book.dat b) Write a function CountData(Author) in Python which accepts the
AuthorName as parameter and count and return number of books by the
given author are stored in the binary file Book.dat.
Input:
import pickle

def File_Data():

with open('book.dat', 'wb') as f:

while True:

Book_no =int(input("Enter book number: "))

Book_name = input("Enter book name: ")

Book_Author = input("Enter book author name: ")

Library = [Book_no, Book_name, Book_Author]

pickle.dump(Library, f)

more = input("Do you want to add more books? (y/n): ").upper()

if more!= 'Y':

break

f.close()

File_Data()

def CountData(Author):

with open('book.dat', 'rb') as f:

count = 0

while True:

try:

a = pickle.load(f)

print(a)

if a[2] == Author:

count += 1

except EOFError:

print(f"Number of books written by {Author}: {count}")

break

Author = input("Enter author name to count books: ")

CountData(Author)
Output:
15. A list contains following record of customer: [Customer Name, Room Type]
Write the following user defined functions to perform the given operations on
the stack named ‘Hotel’: a) Push_Cust()- To push customers’ names of those
customers who are staying in ‘Delux’ Room Type. b) Pop_Cust()- To pop the
names of customers from the stack and display them . Also, display
“Underflow” when there are no customers in the stack. For example: If the
lists with customer details are as follows: [“Siddharth”, “Delux”]
[“Rahul”,”Standard”] [“Jerry”, “Delux”] The stack should contain Jerry
Siddharth The output should be:
Jerry
Siddharth
Underflow
Input:
hotel_list = [["Siddharth", "Delux"],["Rahul","Standard"],["Jerry", "Delux"] ]

l = []

def push():

for i in hotel_list:

if i[1] == "Delux":

print(f'Customers staying in Delux rooms: {i[0]}')

l.append(i[0])

push()

def Pop_Cust(stack):

while True:

if len(stack) !=0:

print(stack.pop())

if len(stack) == 0:

print("Underflow")

print(Pop_Cust(l))

Output:
16. Write a function count_char() that reads a file named
“char.txt” counts the number of times character “a” or “A”
appears in it.
Input:
with open('chart.txt', 'w') as f:

f.writelines(['Hello Ankit\n','I am study in class 12th\n','The India Gate'])

f.close()

with open('chart.txt', 'r') as f:

count = 0

a = f.readlines()

for line in a:

count += line.lower().count('a')

print(f'The letter "a" appears {count} times in the file.')

Output:
17. Write a function called length_line() that reads a file named
“char.txt” and displays the length of each line present in the text
file.
Input:
with open('chart.txt', 'r') as file:
a = file.readlines()
for line in a:
print('the length of words in a line is',len(line.split()))

Output:
18. Write a function count_word() that reads a text file named
“char.txt” and returns the number of times word “ the” exists.
Input:
def count_word(find):
with open('chart.txt', 'r') as f:
count = 0
for line in f:
words = line.split()
count += words.count(find)
if count > 0:
print(f"The word '{find}' appears {count} times in the file.")
else:
print(f"The word '{find}' does not appear in the file.")

find = input("Enter the word to find: ")


count_word(find)

Output:
19. Write a function count Words (in Python to count the words
ending with a digit in a text file "Details.txt". Example: If the file
content is as follows:
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Output will be: 4
Input:
with open('Detail.txt','r')as f:
count = 0
a = f.read()
print(a)
txt = a.split()
for i in txt:
if i[-1].isdigit():
count += 1

print(count)

Output:
20. Write a method/function DISPLAYWORDS() in python to read
lines from a text file STORY.TXT, and display those words, which
are less than 4 characters.
Input:
def displaywords():
with open('story.txt', 'r') as f:
for line in f:
for word in line.split():
if len(word)< 4:
print(word)

displaywords()

Output:

You might also like