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 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 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]) =========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 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('\nElements poped from my_stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) #print(stack.pop()) print('\nmy_stack after elements are poped:') print(stack) ========OUTPUT======== ['1', '2', '3'] Elements poped from my_stack: 3 2 1 my_stack after elements are poped: [ ] Program 11: Read and Write into a file #open a file for writing file=open("E:\klcF.txt","w") #write some text to the file file.write("Welcome to BCA Department\n") L = ['This is BCA College \n', 'Place is Nidasoshi \n', 'Fourth semester \n'] file.writelines(L) #close the file file.close() #open the file for reading file=open("E:\klcF.txt","r") #read the contents of the file into a string variable file_cont=file.read() #print the contents of the file print(file_cont) ===========OUTPUT========== E:\klcF.txt Welcome to BCA Department This is BCA College Place is Nidasoshi Fourth semester 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: 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) ============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'] 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") =========== OUTPUT======== Enter your password:Kavita123@# Valid Password Enter your password:bcacollege Invalid Password Program 3: Demonstrate use of List print("PROGRAM FOR BUILT-IN METHODS OF LIST\n "); demonstrate List numbers=[1,2,13,40,5] print(numbers) sum_of_numbers=sum(numbers) print("Sum=",sum_of_numbers) max_number=max(numbers) print("Max=",max_number) min_number=min(numbers) print("Min=",min_number) numbers.sort() print("sorted numbers in ascending",numbers) numbers.reverse() print("sorted numbers in descending",numbers) numbers.append(6) print("Updated numbers",numbers) numbers.remove(13) print("Removed",numbers) numbers.clear() print("List after clear",numbers) ==========OUTPUT======== PROGRAM FOR BUILT-IN METHODS OF LIST [1, 2, 13, 40, 5] Sum= 61 Max= 40 Min= 1 sorted numbers in ascending [1, 2, 5, 13, 40] sorted numbers in descending [40, 13, 5, 2, 1] Updated numbers [40, 13, 5, 2, 1, 6] Removed [40, 5, 2, 1, 6] List after clear [] Program 4: Demonstrate use of Dictionaries #deomstrate Dictionary person={"name":"Amit","age":"21","city":"Bangaluru","occupation":"student"} #access values in the dictionary print(person["name"]) print(person["age"]) print(person["city"]) print(person["occupation"]) #modify values in the dictionary person["age"]=25 person["occupation"]="Engineer" print(person) #add a new key-value pair to the dictionary person["country"]="India" print(person) #remove a key-value pair from dictonary del person["city"] print(person) #check if key-value exist in the dictionary if "occupation" in person: print("occupation:",person["occupation"]) ============OUTPUT========== Amit 21 Bangaluru student {'name': 'Amit', 'age': 25, 'city': 'Bangaluru', 'occupation': 'Engineer'} {'name': 'Amit', 'age': 25, 'city': 'Bangaluru', 'occupation': 'Engineer', 'country': 'India'} {'name': 'Amit', 'age': 25, 'occupation': 'Engineer', 'country': 'India'} occupation: Engineer 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: 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() =========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... Program 6: Create a GUI using Tkinter module import tkinter as tk from tkinter import messagebox #function to handle button click event def show_message(): messagebox.showinfo("Hello","welcome to the GUI") #create the main window window=tk.Tk() window.title("My GUI") window.geometry("300x200") #create label widget label=tk.Label(window,text="Hello,world") label.pack() #create a button widget button=tk.Button(window,text="click me",command=show_message) button.pack() #start the main event loop window.mainloop() =========OUTPUT========== 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 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() ==========OUTPUT======= 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() ==========OUTPUT========= Program 10:perform arithmetic operations on the Numpy arrays import numpy as np # Initializing our array array1 = np.arange(9, dtype = np.float64).reshape(3, 3) #array1 = np.arange(9, dtype = np.float64) 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)) =========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]] 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...") =========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** View the first few rows of the DataFrame : name Age marks kiran 23 70 savita 20 90 kavya 25 80 sagar 18 70 sumit 21 56 Number of rows and columns in the DataFrame :(11, 3) Filtered data(Age column<25) : name Age marks kiran 23 70 savita 20 90 sagar 18 70 sumit 21 56 sanket 22 50 akash 24 70 10 shilpa 17 65 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...