0% found this document useful (0 votes)
8K views

Write A Program That Reads A Line and Prints Its Statistics Like

The document provides 15 Python programs that perform various tasks like counting characters in a string, creating dictionaries, modifying lists, finding indexes in tuples, calculating simple interest, reading and writing to files, and searching and updating records in binary files. The programs demonstrate how to input and output data, use loops and conditional statements, define and call functions, and work with common Python data types like lists, tuples, dictionaries and files.

Uploaded by

Atharv Chopade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8K views

Write A Program That Reads A Line and Prints Its Statistics Like

The document provides 15 Python programs that perform various tasks like counting characters in a string, creating dictionaries, modifying lists, finding indexes in tuples, calculating simple interest, reading and writing to files, and searching and updating records in binary files. The programs demonstrate how to input and output data, use loops and conditional statements, define and call functions, and work with common Python data types like lists, tuples, dictionaries and files.

Uploaded by

Atharv Chopade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1.

Write a program that reads a line and prints its statistics like:

Number of uppercase

Number of lowercase

Number of alphabets

Number of digits

line=input("Enter a line:")

lowercount=uppercount=0

digitcount=alphacount=0

for a in line:

if a.islower():

lowercount+=1

elif a.isupper():

uppercount+=1

elif a.isdigit():

digitcount+=1

if a.isalpha():

alphacount+=1

print("Number of uppercase letters:", uppercount)

print("Number of lowercase letters:", lowercount)

print("Number of alphabets:", alphacount)

print("Number of digits:", digitcount)

Output:

Enter a line:Hello 123, ZIPPY zippy Zap

Number of uppercase letters: 7

Number of lowercase letters: 11

Number of alphabets: 18

Number of digits: 3
2. Write a Program to create a dictionary containing names of competition winner students
as key and number of their wins as value.

n=int(input("How many students?"))

CompWinners={}

for a in range(n):

key=input("Name of the student:")

value=int(input("Number of competitions won:"))

CompWinners[key]=value

print("The dictionary now is:")

print(CompWinners)

Output:
How many students?5

Name of the student:Naval

Number of competitions won:5

Name of the student:Zainab

Number of competitions won:3

Name of the student:Nita

Number of competitions won:3

Name of the student:Rosy

Number of competitions won:1

Name of the student:Jamshed

Number of competitions won:5


The dictionary now is:
{'Naval': 5, 'Zainab': 3, 'Nita': 3, 'Rosy': 1, 'Jamshed': 5}
3. Given three lists as list1= [‘a’, ‘b’, ‘c’], list2 = [‘h’, ‘i’, ‘t’] and list3 = [‘0’, ‘1’, ‘2’]. Write a
program that adds individual elements of lists 2 and 3 to list1. The resultant list should be
in the order of elements of list3, elements of list1, elements of list2.

list1=['a', 'b', 'c']

list2=['h','i','t']

list3=['0','1', '2']

print("Originally :")

print("List1=", list1)

print("List2=", list2)

print("List3=", list3)

list3.extend(list1)

list3.extend(list2)

print("After adding elements of two lists individually, list now is :")

print(list3)

Output:

Originally :

List1= ['a', 'b', 'c']

List2= ['h', 'i', 't']

List3= ['0', '1', '2']

After adding elements of two lists individually, list now is :

['0', '1', '2', 'a', 'b', 'c', 'h', 'i', 't']


4. Write a program that finds an element's index/position in a tuple WITHOUT using index().

tuple1 = ('a', 'p', 'p', 'l', 'e',)

char=input("Enter a single letter without quotes : ")

if char in tuple1:

count = 0

for a in tuple1:

if a != char:

count += 1

else:

break

print(char, "is at index", count, "in", tuple1)

else:

print(char, "is NOT in", tuple1)

Output:

Enter a single letter without quotes : l

l is at index 3 in ('a', 'p', 'p', 'l', 'e')


5. Program to calculate simple interest using a function interest() that can receive principal
amount, time and rate and returns calculated simple interest. Do specify default values for
rate and time as 10% and 2 years respectively.

def interest (principal, time = 2, rate = 0.10) :

return principal * rate * time

prin=(float(input("Enter principal amount : ")))

print("Simple interest with default ROI and time values is : ")

si1=interest(prin)

print("Rs.", si1)

roi=float (input("Enter rate of interest (ROI) : "))

time=int(input("Enter time in years : "))

print("Simple interest with your provided ROI and time values is : ")

si2= interest (prin, time, roi/100)

print("Rs.", si2)

Output:

Enter principal amount : 6700

Simple interest with default ROI and time values is :

Rs. 1340.0

Enter rate of interest (ROI) : 8

Enter time in years : 3

Simple interest with your provided ROI and time values is :

Rs. 1608.0
6. Displaying the size of a file after removing EOL characters, leading and trailing white
spaces and blank lines

myfile = open(r'E:\poem.txt', "r")

str1 = " "

size = 0

tsize = 0

while str1:

str1= myfile.readline()

tsize = tsize + len(str1)

size = size + len(str1.strip())

print("Size of file after removing all EOL characters & blank lines:", size)

print ("The TOTAL size of the file:", tsize)

Output:

Size of file after removing all EOL characters & blank lines: 360

The TOTAL size of the file: 387


7. Write a program to get roll numbers, names and marks of the students of a class
(get from user) and store these details in a file called "Marks.txt".

count = int(input ("How many students are there in the class?"))

fileout= open ("Marks.txt", "w")

for i in range(count) :

print("Enter details for student", (i+1), "below:")

rollno = int(input("Rollno:"))

name=input("Name :")

marks=float(input ("Marks:"))

rec=str(rollno)+","+name+","+str(marks)+'\n'

fileout.write(rec)

fileout.close()

Output:
How many students are there in the class?3
Enter details for student 1 below:

Rollno:12

Name :Hazel

Marks:67.75
Enter details for student 2 below:

Rollno:15

Name :Jiya

Marks:78.5
Enter details for student 3 below:

Rollno:16

Name :Noor

Marks:68.9
8. Write a program to read a text file line by line and display each word separated by a ‘#’.

myfile = open("Answer.txt", "r")

line=''

while line:

line = myfile.readline()

for word in line.split():

print (word, end = '#')

print()

myfile.close()

Output:

Letter#'a'#is#a#wonderful#letter.#

It#is#impossible#to#think#of #a#sentence#without#it.#

We#know#this#will #never#occur.#

How#mediocre#our#world#would#be#without#this#single#most#powerful#letter.#
9. Write a program to read a text file and display the count of vowels and consonants in the
file.

myfile = open("Answer.txt", "r")

ch=''

vcount=0

ccount=0

while ch:

ch = myfile.read(1)

if ch in ['a', 'A', 'e', 'E', 'i', 'I', 'o', '0', 'u', 'U']:

vcount = vcount + 1

else:

ccount = ccount + 1

print("Vowels in the file:", vcount)

print("Consonants in the file: ", ccount)

myfile.close()
10. Write a program to get student data (roll no., name and marks) from user and write onto a
binary file. The program should be able to get data from the user and write onto the file as
long as the user wants.

import pickle

stu = {}

stufile = open('Stu.dat', 'wb')

ans = 'y'

while ans =='y' :

rno=int(input("Enter roll number: "))

name=input ("Enter name: ")

marks=float (input("Enter marks: "))

stu['Rollno']=rno

stu['Name'] = name

stu['Marks']=marks

pickle.dump(stu, stufile)

ans=input("Want to enter more records?(y/n)…")

stufile.close()

Output:

Enter roll number: 11

Enter name : Sia Enter marks: 83.5

Want to enter more records? (y/n)...y

Enter roll number: 12

Enter name: Guneet

Enter marks: 80.5

Want to enter more records? (y/n)...y

Enter roll number: 13

Enter name : James

Enter marks : 81

Want to enter more records? (y/n)...n


11. Write a program to open file Stu.dat and search for records with roll numbers as 12 or 14.
If found, display the records.

import pickle

stu={}

found=False

fin=open('Stu.dat', 'rb')

searchkeys=[12, 14]

try:

print("Searching in File Stu.dat...")

while True: #it will become False upon EOF exception

stu-pickle.load(fin)

if stu['Rollno'] in searchkeys:

print (stu)

found=True

except EOFError:

if found==False:

print("No such records found in the file")

else:

print("Search successful.")

fin.close()

Output:

Searching in File Stu.dat ...

{'Rollno': 12, 'Name': 'Guneet', 'Marks': 80.5}

{'Rollno': 14, 'Name': 'Ali', 'Marks': 80.5}

Search successful.
12. Read file stu.dat created in earlier programs and display records having marks > 81.

import pickle

stu = {}

found=False

print("Searching in file Stu.dat...")

with open('Stu.dat', 'rb') as fin:

stu pickle.load(fin)

if stu[ 'Marks'] > 81:

print (stu)

found= True

if found== False

print("No records with Marks > 81")

else:

print("Search successful.")

Output:

Searching in file Stu.dat for Marks > 81...

{'Rollno': 11, 'Name': 'Sia', 'Marks': 83.5}

Search successful.
13. Consider the binary file Stu.dat storing student details, which you created in earlier
programs. Write a program to update the records of the file Stu.dat so that those who
have scored more than 81.0, get additional bonus marks of 2.

import pickle

stu= {}

found = False

fin = open('Stu.dat', 'rb+')

try:

while True:

rpos = fin.tell()

stu= pickle.load(fin)

if stu[ 'Marks'] > 81:

stu[ 'Marks'] += 2

fin.seek(rpos)

pickle.dump(stu, fin)

found True

except EOFError

if found == False:

print("Sorry, no matching record found.")

else:

print("Record(s) successfully updated.")

fin.close()

Output:

Record(s) successfully updated.


14. Display the records of file Stu.dat, which you modified in program 5.17(a).

import pickle

stu = {}

fin= open('Stu.dat', 'rb')

try:

print("File Stu.dat stores these records")

while True :

stu= pickle.load(fin)

print (stu)

except EOFError:

fin.close()

Output:

File Stu.dat stores these records

{'Rollno': 11, 'Name': 'Sia', 'Marks': 85.5}

{'Rollno': 12, 'Name': 'Guneet', 'Marks': 80.5}

{'Rollno': 13, 'Name': 'James', 'Marks': 81.0}

{'Rollno': 14, 'Name': 'Ali', 'Marks': 80.5}


15. Write a program to modify the name of rollno 12 as Gurnam in file Stu.dat (created in
earlier programs).

import pickle

stu = {}

found = False

fin = open('Stu.dat', 'rb+')

try:

while True :

rpos = fin.tell()

stu=pickle.load(fin)

if stu['Rollno'] == 12:

stu['Name'] = 'Gurnam'

fin.seek (rpos)

pickle.dump(stu, fin)

found = True

except EOFError:

if found == False:

print("Sorry, no matching record found.")

else:

print("Record(s) successfully updated.")

fin.close()

Output:

File Stu.dat stores these records

{'Rollno': 11, 'Name': 'Sia', 'Marks': 87.5}

{'Rollno': 12, 'Name': 'Gurnam', 'Marks': 80.5}

{'Rollno': 13, 'Name': 'James', 'Marks': 81.0}

{'Rollno': 14, 'Name': 'Ali', 'Marks': 80.5}


16. Write a program to create a CSV file to store student data (Rollno., Name, Marks). Obtain
data from user and write 5 records into the file.

import csv

fh = open("Student.csv", "w")

stuwriter = csv.writer (fh)

stuwriter.writerow(['Rollno', 'Name', 'Marks'] )

for i in range (5):

print("Student record", (i+1) )

rollno = int(input ("Enter rollno: "))

name = input ("Enter name:")

marks = float(input("Enter marks:"))

sturec = [rollno, name, marks]

stuwriter.writerow(sturec)

fh.close()

Output:
Student record 1
Enter rollno:11
Enter name:Nistha
Enter marks:79

Student record 2
Enter rollno:12
Enter name: Rudy
Enter marks:89

Student record 3
Enter rollno:13
Enter name: Rustom
Enter marks:75

Student record 4
Enter rollno:14
Enter name: Gurjot
Enter marks: 89

Student record 5
Enter rollno:15
Enter name:Sadaf
Enter marks:85
17. Write a program to create a csv file by suppressing the EOL translation.

import csv

fh=open("Employee.csv", "w", newline = "")

ewriter=csv.writer (fh)

empdata=[

['Empno', 'Name','Designation','Salary'],

[1001, 'Trupti','Manager', 56000],

[1002, 'Raziya','Manager',55900],

[1003, 'Simran','Analyst',35000],

[1004, 'Silviya','Clerk', 25000],

[1005, 'Suji','PR Officer', 31000]

ewriter.writerows(empdata)

print("File successfully created")

fh.close()

Output:
18. Write a program that copies a text file "source.txt" onto "target.txt" barring the lines
starting with a "@" sign.

def filter (oldfile, newfile) :

fin = open(oldfile, "r")

fout= open(newfile, "w")

while True :

text = fin.readline()

if len(text) == 0:

break

if text [0] == "@":

continue

fout.write(text)

fin.close()

fout.close()

filter("source.txt", "target.txt")

You might also like