# Program 1:Demonstrate usage of basic regular expression import re # Search String str="The rain in spain" x=re.findall("ai",str) print("Search of string 'ai': ",x) x=re.search("\s" ,str) print("The first white-space character is located in position : ",x.start()) x=re.split("\s",str,1) print("Split the string in the occurance of first white-space:",x) x=re.sub("\s","9",str) print("Each white-space is replaced with 9 digit: ",x) print("----------------------------------------------") # Metacharacters x=re.findall("[a-g]",str) print("The letters in between a to g in the string:",x) x=re.findall("spain$",str) if(x): print("\n",str, ": Yes, this string ends with 'spain' word ") else: SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab print("\n No match ") x=re.findall("^The",str) if(x): print("\n",str,": Yes, this string starts with 'The' word") else: print("\n No match") str1="The rain in spain falls mainly in the plain" x=re.findall("ai*",str1) print("\n All ai matching characters:",x) if(x): print("Yes, there is atleast one match") else: print("No match") x=re.findall("all{1}",str1) print("\n The string which contains 'all':",x) if(x): print("Yes, there is atleast one match") else: print("No match") str2="That will be 59 dollars" x=re.findall("\d",str2) print("\n Digits in the string:",x) x=re.findall("do...rs",str2) print("\n Dot metacharacter matches any character:",x) SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ============OUTPUT========== Search of string 'ai': ['ai', 'ai'] The first white-space character is located in position : 3 Split the string in the occurance of first white-space: ['The', 'rain in spain'] Each white-space is replaced with 9 digit: The9rain9in9spain ------------------------------------------------------------------------------ The letters in between a to g in the string: ['e', 'a', 'a'] The rain in spain : Yes, this string ends with 'spain' word The rain in spain : Yes, this string starts with 'The' word All ai matching characters: ['ai', 'ai', 'a', 'ai', 'ai'] Yes, there is atleast one match The string which contains 'all': ['all'] Yes, there is atleast one match Digits in the string: ['5', '9'] Dot metacharacter matches any character: ['dollars'] SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 2: Demonstrate use of advanced regular expressions for - data validation. # importing re library import re p=input("Enter your password:") x=True while x: if(len(p)<6 or len(p)>20): break elif not re.search("[a-z]",p): break elif not re.search("[A-Z]",p): break elif not re.search("[0-9]",p): break elif not re.search("[$#@]",p): break elif re.search("\s",p): break else: print("Valid Password") x=False break if x: print("Invalid Password") SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab =========== OUTPUT======== Enter your password:Kavita123@# Valid Password Enter your password:bcacollege Invalid Password SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 3: Demonstrate use of List print("PROGRAM FOR BUILT-IN METHODS OF LIST\n "); animal = ['Cat','Dog','Rabbit'] print(animal) animal.append('Cow') print("Updated animal lists : ",animal) language = [ 'Python', 'Java', 'C++', 'French', 'c'] return_value = language.pop(3) print("removed element",return_value) print("Updated List : " , language) vowels = [ 'e', 'a', 'u', 'o', 'i'] vowels.sort() print("Sorted list in Ascending : ", vowels) vowels.reverse() print("sorted list in Descending : ",vowels) vowel = ['a', 'e', 'i', 'u'] vowel.insert(3,'o') print("Updated list : " , vowel) animal = ['cat', 'dog', 'rabbit', 'pig'] animal.remove('dog') print('Updated animal lists : ', animal) nums=['1','4','6','6','3','6'] nums.clear() print("list after clear",nums) SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ==========OUTPUT======== PROGRAM FOR BUILT-IN METHODS OF LIST ['Cat', 'Dog', 'Rabbit'] Updated animal lists : ['Cat', 'Dog', 'Rabbit', 'Cow'] removed element French Updated List : ['Python', 'Java', 'C++', 'c'] Sorted list in Ascending : ['a', 'e', 'i', 'o', 'u'] sorted list in Descending : ['u', 'o', 'i', 'e', 'a'] Updated list : ['a', 'e', 'i', 'o', 'u'] Updated animal lists : ['cat', 'rabbit', 'pig'] list after clear [] SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 4:Demonstrate use of Dictionaries thisdict={ "NAME":"Vishal" ,"PLACE":"Sankeshwar" ,"USN":1711745 } print("Directory Content= ",thisdict) x=thisdict["PLACE"] print("\n PLACE is",x) print("\n Keys in the dictionary are:") for a in thisdict: print(a) print("\n Values in this dictionary are: ") for a in thisdict: print(thisdict[a]) print("\n Both keys and values of the dictionary are: ") for x,y in thisdict.items(): print(x,y) print("\n Total items in the dictionary : ",len(thisdict)) thisdict["District"]="Belagavi" print("\n Added new item is = ",thisdict) thisdict.pop("PLACE") print("\n After removing the item from dictionary= ",thisdict) thisdict.clear() print("\n Empty Dictionary= ",thisdict) thisdict={ "NAME":"Vishal" ,"PLACE":"Sankeshwar" ,"USN":1711745 } print("\n Present dictionary content= ",thisdict) mydict=thisdict.copy() print("\n Copy of dictionary is = ",mydict) SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ============OUTPUT========== Directory Content= {'NAME': 'Vishal', 'PLACE': 'Sankeshwar', 'USN': 1711745} PLACE is Sankeshwar Keys in the dictionary are: NAME PLACE USN Values in this dictionary are: Vishal Both keys and values of the dictionary are: Sankeshwar Both keys and values of the dictionary are: 1711745 Both keys and values of the dictionary are: NAME Vishal PLACE Sankeshwar USN 1711745 Total items in the dictionary : 3 Added new item is = {'NAME': 'Vishal', 'PLACE': 'Sankeshwar', 'USN': 1711745, 'District': 'Belagavi'} After removing the item from dictionary= {'NAME': 'Vishal', 'USN': 1711745, 'District': 'Belagavi'} Empty Dictionary= {} Present dictionary content= {'NAME': 'Vishal', 'PLACE': 'Sankeshwar', 'USN': 1711745} Copy of dictionary is = {'NAME': 'Vishal', 'PLACE': 'Sankeshwar', 'USN': 1711745} SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 5:Create SQLite Database and perform operations on tables import sqlite3 # create a connection to a Sqlite database conn=sqlite3.connect('test.db') # create a cursor object cursor=conn.cursor() # create a table cursor.execute("create table emp2(id integer, name tect)") #insert a record into the tables cursor.execute("insert into emp2(id,name) values(101,'ravi')") cursor.execute("insert into emp2(id,name) values(102,'raj')") cursor.execute("insert into emp2(id,name) values(103,'ramesh')") print("\nDisplaying the emp2 table") cursor.execute("select *from emp2") rows=cursor.fetchall() for row in rows: print(row) print("\nafter update and delete the records in the table") # update records in the table cursor.execute("update emp2 set name ='Akash' where id=101") #delete a record from the table cursor.execute("delete from emp2 where id=103") print("Displaying the emp2 table") cursor.execute("select *from emp2") rows=cursor.fetchall() for row in rows: SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab print(row) #drop the table print("\nTable is droped...") cursor.execute("drop table emp2") #commit the transaction conn.commit() #close the cursor and the connections cursor.close() conn.close() SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ==========OUTPUT======= Displaying the emp2 table (101, 'ravi') (102, 'raj') (103, 'ramesh') after update and delete the records in the table Displaying the emp2 table (101, 'Akash') (102, 'raj') Table is droped... SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 6: Create a GUI using Tkinter module import tkinter as tk def show_entry_fields(): print("First Name: %s\n Last Name: %s" % (e1.get(), e2.get())) master = tk.Tk() # master.geometry("250x450") tk.Label(master, text=" GUI ", fg="red", font=('times', 24, 'italic')).grid(row=0) tk.Label(master, text="First Name").grid(row=1) tk.Label(master, text="Last Name").grid(row=2) e1 = tk.Entry(master) e2 = tk.Entry(master) e1.grid(row=1, column=1) e2.grid(row=2, column=1) tk.Label(master, text="Select Gender:", fg="blue").grid(row=3, column=0) R1=tk.Radiobutton(master, text="Male", value=1).grid(row=4, column=0, sticky=tk.W) R2=tk.Radiobutton(master, text="Female", value=2).grid(row=4, column=1, sticky=tk.W) tk.Label(master,text = "Select Age:", fg="blue").grid(row=5, column=0) tk.Spinbox(master, from_= 18, to = 25).grid(row=5, column=1) tk.Label(master, text="Select Subject:", fg="blue").grid(row=6, column=0) tk.Checkbutton(master, text="Java").grid(row=7, column=0, sticky=tk.W) tk.Checkbutton(master, text="Python").grid(row=7, column=1, sticky=tk.W) SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab tk.Checkbutton(master, text="PHP").grid(row=8, column=0, sticky=tk.W) tk.Checkbutton(master, text="C#.Net").grid(row=8, column=1, sticky=tk.W) tk.Label(master,text = "Select District:", fg="blue").grid(row=9, column=0) listbox = tk.Listbox(master) listbox.insert(1,"Belgaum") listbox.insert(2, "Bangalore") listbox.insert(3, "Dharawad") listbox.insert(4, "Hubli") listbox.insert(5, "Mysore") listbox.insert(6, "Mangalore") listbox.grid(row=10,column=1) tk.Button(master, text='QUIT', fg="red", bg="yellow", command=master.quit).grid(row=11, column=0, sticky=tk.W, pady=4) tk.Button(master,text='SHOW', fg="red", bg="yellow", command=show_entry_fields).grid(row=11, column=1, sticky=tk.W, pady=4) tk.mainloop() SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab =========OUTPUT========== SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 7:Demonstrate exceptions in python try: num1=int(input("Enter the numerator:")) num2=int(input("Enter the denominator:")) result=num1/num2 print("Result:",result) except ValueError: print("Invalid input") except ZeroDivisionError: print("Cannot divide by zero") else: print("No exception occur") finally: print("End of program") ===========OUTPUT========== Enter the numerator:12.2 Invalid input End of program Enter the numerator:10 Enter the dinominator:0 Cannot divide by zero End of program SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 8:Drawing Line chart and Bar chart using Matplotlib import matplotlib.pyplot as plt # Data x = [2, 3, 4, 6, 8] y = [2, 3, 4, 6, 8] # Plot the line chart plt.subplot(121) plt.plot(x, y, color='tab:red') # Add labels and title plt.title('Line Chart') plt.xlabel('X axis label') plt.ylabel('Y axis label') # Show the plot plt.subplot(122) plt.title('Bar Chart') plt.xlabel('X axis label') plt.ylabel('Y axis label') plt.bar(x, y) plt.show() SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ==========OUTPUT======= SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 9:Drawing Histogram chart and Pie chart using Matplotlib import matplotlib.pyplot as plt import numpy as np #Generate some random data data=np.random.randint(0,100,100) #create histogram plt.subplot(121) plt.hist(data,bins=20) plt.title("Histogram of random data") plt.xlabel("value") plt.ylabel("frequency") #sample data sizes=[30,25,20,15,10] labels=['A','B','C','D','E'] #create pie chart plt.subplot(122) plt.pie(sizes,labels=labels) plt.title("PIE CHART") plt.show() SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ==========OUTPUT========= SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 10:perform arithmetic operations on the Numpy arrays import numpy as np # Initializing our array array1 = np.arange(9, dtype = np.float_).reshape(3, 3) #array1 = np.arange(9, dtype = np.int_) print('First Array:') print(array1) print('Second array:') array2 = np.arange(11,20, dtype = np.float_).reshape(3, 3) #array2 = np.arange(11,20, dtype = np.int_) print(array2) print('\nAdding two arrays:') print(np.add(array1, array2)) print('\nSubtracting two arrays:') print(np.subtract(array1, array2)) print('\nMultiplying two arrays:') print(np.multiply(array1, array2)) print('\nDividing two arrays:') print(np.divide(array1, array2)) SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab =========OUTPUT======= First Array: Second array: [[0. 1. 2.] [[11. 12. 13.] [3. 4. 5.] [14. 15. 16.] [6. 7. 8.]] [17. 18. 19.]] Adding two arrays: [[11. 13. 15.] [17. 19. 21.] [23. 25. 27.]] Subtracting two arrays: [[-11. -11. -11.] [-11. -11. -11.] [-11. -11. -11.]] Multiplying two arrays: [[ 0. 12. 26.] [ 42. 60. 80.] [102. 126. 152.]] Dividing two arrays: [[0. 0.08333333 0.15384615] [0.21428571 0.26666667 0.3125 ] [0.35294118 0.38888889 0.42105263]] SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 11: Create data frame from Excel sheet using Pandas and perform operations on data frames import pandas as pd #Read data from excel sheets in an Excel file data = pd.read_excel('file.xlsx', sheet_name='kavita') print("\n**Displaying Data from DataFrames**\n") print(data) print("\n**OPERATIONS ON DATAFRAMES**\n") print("\n1.View the first few rows of the DataFrame :") print(data.head()) print("\n2.Number of rows and columns in the DataFrame :",end="") print(data.shape) print("\n3.Filtered data(Age column<25) :") filtered_data =data[data['Age'] < 25] print(filtered_data) print("\n4.Sort DataFrame based on 'Age' col in ascending order :") sorted_data = data.sort_values(by='Age', ascending=True) print(sorted_data) print("\nProgram Closed...") SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab =========OUTPUT========= **Displaying Data from DataFrames** name Age marks 0 kiran 23 70 1 savita 20 90 2 kavya 25 80 3 sagar 18 70 4 sumit 21 56 5 sanket 22 50 6 akash 24 70 7 ramesh 26 40 8 ravi 27 45 9 soumya 28 90 10 shilpa 17 65 **OPERATIONS ON DATAFRAMES** 1.View the first few rows of the DataFrame : name Age marks 0 kiran 23 70 1 savita 20 90 2 kavya 25 80 3 sagar 18 70 4 sumit 21 56 2.Number of rows and columns in the DataFrame :(11, 3) 3.Filtered data(Age column<25) : SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming La