Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 1 Semester – III Course Name : Python Programming Laboratory Course Code : 20 I S38 No. of Lecture Hours / Week : 01 CIE Marks : 50 No. of Tutorial / Practical Hours / Week : 02 SEE Marks : 50 Total No. of Lecture + Tutorial / Practical Hours : 32 SEE Duration : 03 hr. L:T:P : 1 :0:2 Credits : 02 Course Overview The laboratory course Python Application Programming aims to introduce the students about the basics of writing and running python scripts. The students will be able to enhance their analyzing and problem - solving skills by implementing suitable functionali ty using core data structures like lists, dictionaries, tuples and sets in Python to store, process, and sort the data. Course Learning Objectives (CLO) The course should enable the students to • Learn the syntax and semantics of Python • Interpret the use of procedural statement like assignment, conditional statements, loops and function call • Demonstrate the use of built - in functions • Infer the supported data structures like list, dictionaries, and tuples in Python • Describe the need for Object - oriented programming concepts in Python Part – A 1. Develop a Python program to a) Calculate the sum of digits of an input number & repeat it until you get single digit. If resultant sum is equal to 1 the n print it as a Magic number. b) Print all prime numbers smaller than or equal to a specified number 2. Design a Python program to implem ent the Rock - Paper - Scissor game. 3. Develop a Python program to a) Extract substring present between @ and # b) Count occurrence of character ‘e’ in a string without using built - in method c) Remove the word “the” present in a string without using replace() method d) Count the total number of apples bought by the guests in the given dictionary AllGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} 4. Develop a Pyt hon program to a) Accept a string and display the string in reverse order. The displayed string must contain all characters at the even position of accepted string ignoring the blank spaces b) Print all ‘;’ separated email IDs pr esent in a string without usin g List c) C ount the occurrence of all the characters in the string Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 2 5. Develop a Python program to implement the Hangman Game (guessing game) for two or more players. One player thinks of a word, phrase or sentence and the other(s) tries to guess it by suggesti ng letters or numbers, wit hin a certain number of guesses. 6. Develop a Python program to a) Print all words present in a string along with their length and total words present in the string b) Display first ‘n’ Fibonacci numbers in reverse order 7. Design a Python progr am using Regular expressions to a) Extract Email IDs from a given text. b) Validate the user password with minimum length=6 and maximum length=16 and must have at least one lower - case letter, upper - case letter, number and special symbol (#, @, $, _). 8. Perform the following file operations using Python program: a) Traverse a path and display all the files and subdirectories in each level till the deepest level for a given path. Also, display the total num ber of files and subdirectories. b) Read a file content and c o py only the conten ts at odd lines into a new file. 9. Develop an application using ‘tkinter’ package to randomly assign program numbers for students and store the assigned details in a CSV file. 10. Create an Interact ive Dictionary Application in Python by reading the external JSON file which contains words and different meanings associated with it. Program will ask the user for a word and returns the meaning for the user given word from the JSON file, if the actual me aning is not available for the user given word, the program should through suggestion to user by analyzing the word to check if a user somehow mistypes the word and meant something else. 1. Develop a Python program to a) Calculate the sum of digits of an input number & repeat it until you get single digit. If resultant sum is equal to 1 then print it as a Magic number. # method to find sum of digits # of a number until sum becomes Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 3 # single digit n=input('Enter a Number to find sum of all Digit s ') n=int(n) m=n sum = 0 while(n > 0 or sum > 9): if(n == 0): n = sum sum = 0 sum += n % 10 n //= 10 print('Sum of all digits in a Number '+str(m)+' ís: '+str(sum)) if(sum==1): print("Its Magic Number") else: print("Its not Magic Number") b) Print all prime numbers smaller than or equal to a specified number # Python program to print # all prime numbers less than N start = 2 print ("Enter the limit to print Prime Numbers ") end = int(input()) print ("Prime Numbers upto limit ",end,"are :") for i in range(start, end+1): count=1 for j in range(2, i): if(i % j == 0): count=count+1 if (count == 1): print(i) Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 4 2. Design a Python program to implement the Rock - Paper - Scissor game # import random module import random # Print multiline instruction # perform string concatenation of string print("Winning Rules of the Rock paper scissor game as follows: \ n" +"Rock vs paper - >paper wins \ n" + "Rock vs scissor - >Rock wins \ n" +"paper vs scissor - >scissor wins \ n") while True: print("Enter choice \ n 1. Rock \ n 2. paper \ n 3. scissor \ n") # take the input from user choice = int(input("User turn: ")) # OR is the short - circuit operator # if any one of the condition is true # then it return True value # looping until user enter invalid input while choice > 3 or choice < 1: choice = int(input("enter valid input: ")) # initialize value of choice_name variable # corresponding to the choice value if choice == 1: choice_name = 'Rock' elif choice == 2: choice_name = 'paper' else: choice_name = 'scissor' # print user choice print("user choice is: " + choice_name) print(" \ nNow its computer turn.......") # Computer chooses randomly any number # among 1 , 2 and 3. Using randint method # of random module comp_choice = random.randint(1, 3) Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 5 # looping until com p_choice value # is equal to the choice value while comp_choice == choice: comp_choice = random.randint(1, 3) # initialize value of comp_choice_name # variable corresponding to the choice value if comp_choice == 1: comp_choice_name = 'Rock' elif comp_choice == 2: comp_choice_name = 'paper' else: comp_choice_name = 'scissor' print("Computer choice is: " + comp_choice_name) print(choice_name + " V/s " + comp_choice_name) # condition for winning if((choic e == 1 and comp_choice == 2) or (choice == 2 and comp_choice ==1 )): print("paper wins => ", end = "") result = "paper" elif((choice == 1 and comp_choice == 3) or (choice == 3 and comp_choice == 1)): print("Rock wins =>", end = "") result = "Rock" else: print("scissor wins =>", end = "") result = "scissor" # Printing either user or computer wins if result == choice_name: print("<== User wins ==>") else: print("<== Computer wins ==>") print("Do you want to play again? (Y/N)") ans = input() # if user input n or N then condition is True if ans == 'n' or ans == 'N': break Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 6 # after coming out of the while loop # we print thanks for playing print(" \ nThanks for playing") 3. Develop a Python program to a) Extract substring present betweem @ and # str="Good@morning#have a nice day" index1 = str.find('@') #4 index2 = str.find('#') #12 substr = str[index1+1 : index2] print(substr) b) Count occurrence of character ‘e’ in a string without using b uilt - in method count = 0 str = input(“Enter a String \ n”) for letter in str: if letter == 'e ': count = count+1 print (count) c) Remove the word “the” present in a string without using replace() method str='this is the sentence' l=str.split() while(‘the’ in l): l.remove(‘the’) delimiter=' ' str=delimiter.join(l) print(str) d) Count the total number of apples bought by the guests in the given dictionary AllGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} fruit = 'apples' numBrought = 0 for k,v in allGuests.items(): numBrought = numBrought + v.get(fruit, 0) print(numBrought) 4. Develop a Python program to Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 7 a) Accept a string and display the string in reverse order. The displayed string must contain all characters at the even position of accepted string ignoring the blank spaces. str = input("Enter a string") print("the complete reverse d string is:") print(str [ : : - 1] ) s2 = str.replace(' ','') evenstr = s2[1: : 2] rev = evenstr[ : : - 1] print("the required reversed string is:") print( rev ) b) Print all ‘;’ separated email IDs present in a string without using List str = ";abc@gmail.com;def@gmail.com;ghi@gmail.com;" index1 = str.find(';') index2 = str.find(';',index1+1) while(index2!= - 1): substr = str[index1+1 : index2] print(substr) index1 = index2 i ndex2 = str.find(';',index1+1) c) C ount the occurrence of all the characters in the string. str='good morning' D=dict() for ch in str: if ch in D: D[ch]=D[ch]+1 else: D[ch]=1 print(D) (Or) str='good morning' D=dict(); for ch in str: D[ch]=D.get(ch,0)+1 print('Occurence of Each Characters: \ n', D) Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 8 5. Develop a Python program to implement the Hangman Game (guessing game) for two or more players. One player thinks of a word, phrase or sentence and the other(s) tries to guess it by suggesting letters or numbers, within a certain number of guesses. name = input ( "What is your name? " ) print ( f "Hello { name } , Time to play hangman!" ) print ( "Start guessing..." ) print ( "HINT: word is the name of a fruit \ n " ) word = "apple" guesses = "" turns = len ( word ) + 2 while turns > 0 : failed = 0 for char in word : if char in guesses : print ( char ) else : print ( "_" ) failed += 1 if failed == 0 : print ( "You won the game : - )" ) break guess = input ( "Guess a character: " ) guesses += guess if guess not in word : turns - = 1 print ( "Wrong guess" ) print ( f "You have { turns } more guesses" ) if turns == 0 : print ( "You lost the game : - (" ) 6. Develop a Python program to a) Print all words present in a string along with their length and total words present in the string. str="how are you" L = str.split() print(L) count=0 for word in L: Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 9 print(word,":",len(word)) count+=1 print("number of words:",count) b) Display first ‘n’ Fibonacci numbers in reverse order. # Python 3 Program to print Fibonacci # series in reverse order def reverseFibonacci(n): a = [0] * n # assigning first and second elements a[0] = 0 a[1] = 1 for i in range(2, n): # storing sum in the # preceding location a[i] = a[i - 2] + a[i - 1] for i in range(n - 1, - 1 , - 1): # printing array in # reverse order print(a[i],end=" ") n = input ('Enter the range of Fibonacci Series to print in reverse order \ n') n = int(n) reverseFibonacci(n) 7. Design a Python program using Regular expressions to a) Extract Email IDs from a given text. i mport re emailRegex = re.compile(r'''( [a - zA - Z0 - 9._%+ - ]+ # username @ # @ symbol [a - zA - Z0 - 9. - ]+ # domain name ( \ .[a - zA - Z]{2,4}) #dot - something )''',re.VERBOSE) matches = [] text = "xyz@gmil.com and abc_987@vvce.ac.in are the mail ids. (897) - 012 - 3456 ext.23 and 897.012 - 3456x23 are numbers" Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 10 for groups in emailRegex.findall(text): matches.append(groups[0]) print(matches) b) Validate the user password with minimum length=6 and maximum length=16 and must have at least one lower - case letter, upper - case letter, number and special symbol (#, @, $, _). import re p= input("Input your password") x = True while x: if (len(p)<6 or len(p)>12): break elif not re.search("[a - z]",p): break elif not re.search("[0 - 9]",p): break elif not re.search("[A - Z]",p): break elif not re.search("[$#@ _ ]",p): break elif re.search(" \ s",p): break else: print("Valid Password") x=False break if x: print("Not a Valid Password") 8. Perform the following file operations using Python program: a) Traverse a path and display all the files and subdirectories in each level till the deepest level for a given path. Also, display the total number of files and subdirectories. import os print("Enter path to traverse: ") root_dir = input() if os.path.exists(root_dir): dir_count = 0 file_count = 0 for dir_name, sub_dir_list, file_list in os.walk(root_dir): print(f"Found directory: { dir_name } \ n ") if os.path.normpath(root_dir) != os.path.normpath(dir_name): dir_count += 1 for each_file_name in file_list: Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 11 file_count += 1 print(f"File name(s) { each_file_name } \ n ") prin t(f"Number of subdirectories are { dir_count } \ n ") print(f"Number of files are { file_count } \ n ") display_menu() else : print("Entered path doesn't exist") b) Read a file content and copy only the contents at odd lines into a new file. source_file = input("Enter the Source file name: ") destination_file = input("Enter the Destination file name: ") try : with open(source_file) as in_file, open(destination_file, "w") as out_file: list_of_line s = in_file.readlines() for i in range(0, len(list_of_lines)): if i % 2 != 0: out_file.write(list_of_lines[i]) except IOError : print("Error in file names") 9. Develop an application using ‘tkinter’ package to randomly assign program numbers for students and store the assigned details in a CSV file. import random import csv from tkinter import * ; from tkinter.ttk import * from datetime import datetime from datetime import date root2=Tk() root2.configure(bg="orange") """C = Canvas(root2, bg="blue", height=250, width=300) filename = PhotoImage(file = "C: \ \ Users \ \ Vijay \ \ vijj.png") background_label = Label(root2, image=filename) background_label.place(x=0, y=0, relwidth=1, relheight=1)""" root2.title("Auto Program Generator - ISE") root2.geometry("600x300") Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 12 student=[['USN','Name','Program Assigned','Time']] def textfile(pgm,rl,name): rn="4VV20IS"+rl.upper() to=str(datetim e.now()) student.append([rn,name,pgm,to]) root3=Tk() root3.title("PROGRAM DISPLAY") root3.configure(bg="green") root3.geometry("1200x300") lb1=Label(root3 , text="Python Laboratory - Department of ISE - Lab Internals "+" \ n \ n"+" \ t \ t Your Lab program is: " +" \ n \ n"+""+pgm+' \ n \ n'+' \ t \ t Generated at \ t \ t'+to,font='Helvetica 9 bold') lb1.pack() root3.mainloop() print(student) def generate(): n=random.randint(1,6) print("your Program is",n) l1=[" ","1. " ,"2. ","3. ","4. ","5. ","6. "] print(l1) root4=Tk() root4.title("Student Roll NUmber") root4.configure(bg="white") root4.geometry("300x200") roll_no=Label(root4,text="Enter Student Roll Number ") roll_no_g=Entry(root4) s_name=Label(root4,text="Enter Student Name ") s_name_g=Entry(root4) roll_no.pack() roll_no_g.pack() s_name.pack() s_name_g.pack() bt3=But ton(root4,text='ok',command=lambda:textfile(l1[n],str(roll_no_g.get()),str(s_name_g.get()))) bt3.pack(side=TOP,pady=0) def close(): fname=batch_ent.get()+".csv" with open(fname,'w',newline='') as n_4: csv_writer=csv.writer(n_4,delimiter=",") for i in student: csv_writer.writerow(i) Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 13 L1=Label(root2,text="Enter Batch") L1.pack(side=TOP,pady=10) batch_ent=Entry(root2) batch_ent.pack(side=TOP,pady=10) Bt1=Button(root2,text="generate",command=lambda:generate()) Bt1.pack(side=TOP,pady=20) Bt1=Button(root2,text="Done",command=lambda:close()) Bt1.pack(side=TOP,pady=20) Lab=Label(root2,text="Tkinter Program - ISE - VVCE - Mysuru") Lab.pack(side=BOTTOM) root2 .mainloop() 10. Create an Interactive Dictionary Application in Python by reading the external JSON file which contains words and different meanings associated with it. Program will ask the user for a word and returns the meaning for the user given word from the JSON file, if the actual meaning is not available for the user given word, the program should through suggestion to user by analyzing the word to check if a user somehow mistypes the word and meant something else. import json from diffl ib import get_close_matches words_data = json load ( open ( "words.json" )) def word_meaning(word): word = word.lower() if word in words_data: return words_data[word] elif word.title() in words_data: return words_data[word.title()] elif word.upper() in words_data: return words_data[word.upper()] elif len(get_close_matches(word, words_data.keys())) >0: similar_words_list = list(map(str, get_close_matches(word, words_data.keys()))) ans = input("Did you mean %s instead? Enter 'Y' If yes or 'N' if No " % similar_words_list) if ans.lower() == 'y ': index = input("Enter the position number of word to select the word. Ex 1 or 2 or 3 : ") return word_meaning(get_close_matches(word, words_data.keys())[int(index) - 1]) elif ans.lower() == 'n': Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 14 print("Word Doesnt exists. Please double check it!!!") else: print("Sorry, We don't understand you!!!!") else: print("Sorry, We don't understand you!!!!") word = input(“Enter a word to know its meaning : “ ) meaning = word_meaning(word) pr int(“The meaning of the word is : “ meaning); Vidyavardhaka College of Engineering Gokulam III stage, Mysuru – 570 002 Autonomous Institute under Visvesvaraya Technological University (VTU) Accredited by NBA (2020 - 2023) & NAAC with ‘A’ Grade (2018 - 2023) 15 Part B Open - Ended Experiments: The student can choose to solve any one open - ended problem to illustrate python application in the d omains specified below (but not restricted to ) using various python packages • Excel file handling • PDF/word file manipulation • CSV file analysis • Web scraping • Cha t bot • Image processing • Database Management • Network Programming • GUI development for python application • Simple Games Experiment Weightage Type of Experiment Program - No Weightage Demonstration 1, 5 20% Exercise 2,8,9 30% Structured Enquiry 3,6,7,10 40% Open ended enquiry 4 10% Course Outcomes (COs) At the end of the course, students will be able to CO1 Demonstrate the usage of Python language syntax including control s tatements, loops, and functions CO2 Design and Develop Python programs to implement the core data structures like lists , dictionaries, tuples and sets CO3 Employ various IDEs for the development of python application for the given problem CO – PO – PSO Mapping PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3 CO1 2 2 CO2 3 3 CO3 1 1 Avg. 2 3 1 2