CBSE Class 12: Python Important Programs 3

Program:7.
Write a Python program to pass a Dictionary to a function and display it.

def show_dic(n):
	for i in n:
		print(i,n[i])

def main():
	n={101:'Amit',102:'Mohan',103:'mohit',104:'Sohan',105:'Kishan'}
	show_dic(n)

"""
if __name__=='__main__':
	main()
"""
#or
#function calling
main()

Output:

101 Amit
102 Mohan
103 mohit
104 Sohan
105 Kishan

Program:8.
Write a program to read a text file ‘story.txt’. Count and print the number of lines starting with letter ‘A’ present in the file.

def read_file():
	filepath = 'story.txt'
	with open(filepath) as fp:
	    line = fp.readline()
	    cnt = 1
	    while line:
	        if(line[0]=='a' or line[0]=='A'):
	            #print(line)
	            print("Line {}: {}".format(cnt, line.strip()))
	            cnt=cnt+1
	        line = fp.readline()

def main():
	read_file()

"""
if __name__=='__main__':
	main()
"""
#or
#function calling
main()

Program:9.
Write a program to read a text file ‘story.txt’. Count and print the total number of words and length of each word present in the file.

def count_words():
	w=0
	with open("abc.txt") as f:
		for line in f:
			for word  in line.split():
				print(word,"  ",len(word))
				w=w+1
		print("total words  ",w)

def main():
	count_words()

"""
if __name__=='__main__':
	main()
"""
#or
#function calling
main()