A2 python

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<n:
 c=a+b
 b=a
 a=c
 if c==n:
 print("Yes,the number belongs to Fibonacci series")
 else:
print("No, the number not belongs to Fibonacci series")
==========OUTPUT=========
Enter the number: 5
Yes the number belongs to fibonacci series
Enter the number: 4
No the number not belongs to fibonacci series
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
Program 2: Solve Quadratic Equations
#import complex math module
import cmath
print("Enter the value of a")
a=float(input())
print("Enter the value of b")
b=float(input())
print("Enter the value of c")
c=float(input())
#calculate the discriminant
d=(b**2)-(4*a*c)
#find the solution
soln1=(-b-cmath.sqrt(d))/(2*a)
soln2=(-b+cmath.sqrt(d))/(2*a)
#print("The solution are")
print("solution1=",soln1)
print("solution2=",soln2)
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
=========OUTPUT=======
Enter the value of a
1
Enter the value of b
2
Enter the value of c
3
solution1= (-1-1.4142135623730951j)
solution2= (-1+1.4142135623730951j)
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
Program 3: Find the sum of natural numbers
num = int (input("Enter a number: ")) 
if num< 0:
print("Enter a positive number")
else:
 sum = 0 
 while (num> 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<num:
 if num%i == 0:
 flag = 1
 print (num,"is NOT a prime number!");
i = i + 1
if flag == 0:
 print (num,"is a prime number!");
=========OUTPUT========
Please enter a number:7
7 is a prime number!
Please enter a number:4
4 is NOT a prime number!
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
Program 6: Implement sequential search
def lin_search(list1,n,key):
 for i in range(0,n):
 if(list1[i]==key):
 return i
 return -1
n=int(input("Enter the size"))
list1=input("Enter the numbers:").split()
list1=[int(x)for x in list1]
key=int(input("Enter the key Element to be searched"))
n=len(list1)
res=lin_search(list1,n,key)
if(res==-1):
print("Element not found")
else:
print("Element found at index:",res)
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
==========OUTPUT=======
Enter the size:5
Enter the numbers:2 4 23 7 50
Enter the key Element to be searched:23
Element found at index: 2
Enter the size:4
Enter the numbers:1 2 3 43 
Enter the key Element to be searched:10
element not found
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
Program 7: Create a calculator program
def add(x, y):
 return x + y
def subtract(x, y):
 return x - y
def multiply(x, y):
 return x * y
def divide(x, y):
 return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
 choice = input("Enter choice(1/2/3/4): ")
 if choice in ('1', '2', '3', '4'):
 try:
 num1 = float(input("Enter first number: "))
 num2 = float(input("Enter second number: "))
 except ValueError:
print("Invalid input. Please enter a number.")
 continue
 if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
next_calculation = input("Let's do next calculation? (yes/no): ")
 if next_calculation == "no":
 break
 else:
print("Invalid Input")
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
============OUTPUT==========
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 1
Enter first number: 23
Enter second number: 12
23.0 + 12.0 = 35.0
Let's do next calculation? (yes/no): yes
Enter choice(1/2/3/4): 2
Enter first number: 12
Enter second number: 6
12.0 - 6.0 = 6.0
Let's do next calculation? (yes/no): no
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
Program 8:Explore string functions
str1=input("Enter the first string:")
str2=input("Enter the second string:")
print("conversion of uppercase of",str1,"is",str1.upper())
print("conversion of lowercase of",str2,"is",str2.lower())
print("swapcase of string",str1,"is",str1.swapcase())
print("title-case-of string",str1,"is",str1.title())
print("string replacement of first string",str1,"is",str1.replace(str1,str2))
string="python is awesome"
capitalized_string=string.capitalize()
print("\n old string ",string)
print("capitalized string",capitalized_string)
name="bcacollegenidasoshi"
if name.isalpha()==True:
print("All characters are alphabets")
else:
print("All characters are not alphabets")
print("Maximum is",max(1,2,3,4))
num=[1,3,2,8,5,10,6]
print("Maximum number is:",max(num))
teststring="python"
print("Length of",teststring,"is",len(teststring))
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
===========OUTPUT=========
Enter the first string:bca
Enter the second string:NIDASOSHI
conversion of uppercase of bca is BCA
conversion of lowercase of NIDASOSHI is nidasoshi
swapcase of string bca is BCA
title-case-of string bca is Bca
string replacement of first string bca is NIDASOSHI
old string python is awesome
capitalized string Python is awesome
All characters are alphabets
Maximum is 4
Maximum number is: 10
Length of python is 6
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
Program 9: To implement selection sort
# Initialize an empty list
array = []
print("Enter the limit")
n=int(input())
for i in range(n):
 element = int(input("Enter the Element: "))
array.append(element)
for i in range(n-1):
 min = i
 for j in range(i+1, n):
 if array[min] > 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('\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) 
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
#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)
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
===========OUTPUT==========
E:\klcF.txt
Welcome to BCA Department
This is BCA College 
Place is Nidasoshi 
Fourth semester
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 ");
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)
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
==========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 []
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
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"])
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
============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
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:
 print(row)
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
#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...
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
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()
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.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)) 
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)
SNJPSNMS Trust’s Degree College,Nidasoshi
Python Programming Lab
3.Filtered data(Age column<25) :
 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..

Popular posts from this blog

devil

html