SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program1: check whether the number is belongs to Fibonacci series or not PART A n=int(input("Enter the number: ")) c=0 a=1 b=1 if n==0 or n==1: print("Yes the number belongs to fibonacci series") else: while c 0): sum += num num-=1 print("The sum is:", sum) ========OUTPUT======== Enter a number: 10 The sum is: 55 SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 4: Display Multiplication table num = int(input("Display multiplication table of? ")) # Iterate 10 times from i = 1 to 10 for i in range(1, 11): print(num, 'x', i, '=', num*i) ===========OUTPUT======= Display multiplication table of? 5 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50 SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 5: To check if a number is prime or not num = int(input('Please enter a number:')) i = 2 flag = 0 while i array[j]: min = j if min != i: temp = array[i] array[i] = array[min] array[min] = temp print("The Sorted array in ascending order:", end='\n') for i in range(n): print(array[i]) SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab =========OUTPUT======== Enter the limit 5 Enter the Element: 12 Enter the Element: 2 Enter the Element: 5 Enter the Element: 23 Enter the Element: 1 The Sorted array in ascending order: 1 2 5 12 23 SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 10: To implement stack # initial empty stack stack = [ ] # append() function to push # element in the stack stack.append('1') stack.append('2') stack.append('3') print(stack) # pop() function to pop # element from stack in # LIFO order print('\n Elements poped from my_stack:') print(stack.pop( )) print(stack.pop( )) print(stack.pop( )) #print(stack.pop( )) print('\n my_stack after elements are poped:') print(stack) SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ========OUTPUT======== ['1', '2', '3'] Elements poped from my_stack: 3 2 1 my_stack after elements are poped: [] SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab Program 11: Read and Write into a file # Program to show various ways to read and write data in a text file. # File Operations: Read Only ('r’), Read and Write ('r+’), Write Only ('w’), # Write and Read ('w+’), Append Only ('a’), Append and Read (‘a+’) file = open("E:\klcnew.txt","w") L = ['This is BCA College \n', 'Place is Nidasoshi \n', 'Fourth semester \n'] # assigned this ["This is BCA College \n", "Place is Nidasoshi \n", "Fourth semester \n"] to variable L file.write("Hello Python \n") file.writelines(L) file.close() # use the close() to change file access modes file = open("E:\klcnew.txt","r+") print("Output of the Read function is ") print(file.read()) print() # The seek(n) takes the file handle to the nth byte from the start. file.seek(0) print( "The output of the Readline function is ") print(file.readline()) print() SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab file.seek(0) # To show difference between read and readline print("Output of Read(12) function is ") print(file.read(12)) print() file.seek(0) print("Output of Readline(8) function is ") print(file.readline(8)) file.seek(0) # readlines function print("Output of Readlines function is ") print(file.readlines()) print() file.close() SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab ============OUTPUT========== Output of the Read function is Hello Python This is BCA College Place is Nidasoshi Fourth semester The output of the Readline function is Hello Python Output of Read(12) function is Hello Python Output of Readline(8) function is Hello Py Output of Readlines function is ['Hello Python \n', 'This is BCA College \n', 'Place is Nidasoshi \n', 'Fourth semester \n'] SNJPSNMS Trust’s Degree College,Nidasoshi Python Programming Lab PART B # 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 Lab name Age marks 0 kiran 23 70 1 savita 20 90 3 sagar 18 70 4 sumit 21 56 5 sanket 22 50 6 akash 24 70 10 shilpa 17 65 4.Sort DataFrame based on 'Age' col in ascending order : name Age marks 10 shilpa 17 65 3 sagar 18 70 1 savita 20 90 4 sumit 21 56 5 sanket 22 50 0 kiran 23 70 6 akash 24 70 2 kavya 25 80 7 ramesh 26 40 8 ravi 27 45 9 soumya 28 90 Program Closed...