Python Lab Manual
Python Lab Manual
PYTHON PROGRAMS
Part-A
1. Check if a number belongs to the Fibonacci sequence
2. Solve Quadratic Equations
3. Find the sum of n natural numbers
4. Display Multiplication Tables
5. Check if a given number is a Prime Number or not
6. Implement a sequential search
7. Create a calculator program
8. Explore string functions
9. Implement Selection Sort
10. Implement Stack
11. Read and write into a file
Part-B
1. Demonstrate usage of basic regular expression
2. Demonstrate use of advanced regular expressions for data validation.
3. Demonstrate use of List
4. Demonstrate use of Dictionaries
5. Create SQLite Database and Perform Operations on Tables
6. Create a GUI using Tkinter module
7. Demonstrate Exceptions in Python
8. Drawing Line chart and Bar chart using Matplotlib
9. Drawing Histogram and Pie chart using Matplotlib
10. Create Array using NumPy and Perform Operations on Array
11. Create DataFrame from Excel sheet using Pandas and Perform Operations on
DataFrames
PART – A
# generating the Fibonacci numbers until the generated number is less than N
while f3 < n:
f3 = f1 + f2
f2 = f1
f1 = f3
if f3 == n:
print("Given number is Fibonacci number")
else:
print("No it’s not a Fibonacci number")
OUTPUT:
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
OUTPUT:
Enter a: 2
Enter b: 3
Enter c: 4
The solution are (-0.75-1.1989578808281798j) and (-0.75+1.1989578808281798j)
OUTPUT:
OUTPUT:
Enter a number: 5
The Multiplication Table of: 5
5x1=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
OUTPUT:
Enter a number=3
3 is a prime number
Enter a number=6
6 is not a prime number
OUTPUT:
if choice == 'a':
print(num_1, " + ", num_2, " = ", add(num_1, num_2))
else:
print("This is an invalid input")
OUTPUT:
OUTPUT:
def selection_sort(array):
for i in range(0, len(array) - 1):
smallest = i
for j in range(i + 1, len(array)):
if array[j] < array[smallest]:
smallest = j
array[i], array[smallest] = array[smallest], array[i]
OUTPUT:
list=[]
list.append(1) # append 1
print("push:", list)
list.append(2) # append 2
print("push:", list)
list.append(3) # append 3
print("push:", list)
list.pop() # pop 3
print("pop:", list)
print("peek:", list[-1]) # get top most element
list.pop() # pop 2
print("pop:", list)
print("peek:", list[-1]) # get top most element
OUTPUT:
push: [1]
push: [1, 2]
push: [1, 2, 3]
pop: [1, 2]
peek: 2
pop: [1]
peek: 1
OUTPUT:
Hello world!
PART – B
import re
text = "Hello BCA Students! Welcome to 4th Sem"
#re.match() tries to match a pattern at the beginning of the string.//
match = re.match("Hello", text)
print("Match:", match.group() if match else None)
#re.search() searches the string for a match, and returns a match object if there is a
match.//
search = re.search("BCA", text)
print("Search:", search.group() if search else None)
#re.findall() returns a list containing all matches.//
findall = re.findall(r"[0-9]", text)
print("Findall:", findall)
#re.split() returns a list where the string has been split at each match.//
split = re.split(" ", text) # Splitting by space instead of "ls"
print("Split:", split)
#re.sub() replaces the matches with the text of choice.//
sub = re.sub("4th", "Fourth", text) # Replacing "4th" with "Fourth"
print("Sub:", sub)
OUTPUT:
Match: Hello
Search: BCA
Findall: ['4']
Split: ['Hello', 'BCA', 'Students!', 'Welcome', 'to', '4th', 'Sem']
Sub: Hello BCA Students! Welcome to Fourth Sem
import re
def validate_data():
email = input("Enter your email address: ")
phone = input("Enter your phone number: ")
url = input("Enter a URL: ")
password = input("Enter your password: ")
#Simple regular expressions for validation
email_regex = r'\S+@\S+\.\S+'
phone_regex = r'\d{10}'
url_regex = r'https?://(www\.)?\S+'
password_regex = r'.{8,}'#Any character, minimum length of 8
if not re.fullmatch(email_regex, email):
print("Invalid Email address")
if not re.fullmatch(phone_regex, phone):
print("Invalid Phone number")
if not re.fullmatch(url_regex, url):
print("Invalid URL")
if not re.fullmatch(password_regex, password):
print("Invalid password. It should be a minimum of 8 characters long.")
#Run the function
validate_data()
OUTPUT:
Invalid URL
Invalid password. It should be a minimum of 8 characters long.
OUTPUT:
#Define a Dictionary
my_dict={'name':'Arun','age':40,'city':'Bangalore'}
print("Initial Dictionary:",my_dict)
#Get Value with get mthod which provides a default value if the key is not in the
dictionary
print("Value for 'country' with default:",my_dict.get('country','India'))
print("Popped item:",my_dict.pop('job'))
print("Dictionary after popping an item:", my_dict)
OUTPUT:
Dictionary after adding an item: {'name': 'Arun', 'age': 35, 'city': 'Bangalore', 'job':
'Engineer'}
Dictionary after deleting an item by key: {'name': 'Arun', 'age': 35, 'job': 'Engineer'}
Popped item: Engineer
Dictionary after popping an item: {'name': 'Arun', 'age': 35}
Keys: ['name', 'age']
Values: ['Arun', 35]
Items: [('name', 'Arun'), ('age', 35)]
Number of items: 2
'name' in dictionary: True
'city' in dictionary: False
Dictionary after merging: {'name': 'Arun', 'age': 35, 'country': 'India', 'job': 'Engineer'}
Dictionary after clearing: {}
import sqlite3
def display_rows(cursor):
rows=cursor.fetchall()
for row in rows:
print(row)
#Insert a record
cursor.execute("INSERT INTO emp VALUES(1,'Arun',50000,'IT')")
cursor.execute("INSERT INTO emp VALUES(2,'Asha',40000,'HR')")
cursor.execute("INSERT INTO emp VALUES(3,'Raj',55000,'Admin')")
conn.commit()
print("Records inserted")
#Update a record
cursor.execute("UPDATE emp SET salary=100000 WHERE empno=1")
conn.commit()
print("Record updated")
#Delete a record
cursor.execute("DELETE FROM emp WHERE empno=1")
conn.commit()
print("Record deleted")
OUTPUT:
Table Created
Records inserted
Records in the tables:
(1, 'Arun', 50000.0, 'IT')
(2, 'Asha', 40000.0, 'HR')
(3, 'Raj', 55000.0, 'Admin')
Record updated
Records in the table after update:
(1, 'Arun', 100000.0, 'IT')
(2, 'Asha', 40000.0, 'HR')
(3, 'Raj', 55000.0, 'Admin')
Record deleted
Records in the table after deletion:
(2, 'Asha', 40000.0, 'HR')
(3, 'Raj', 55000.0, 'Admin')
Table dropped
import tkinter as tk
from tkinter import messagebox,ttk
def submit():
messagebox.showinfo("Submitted","Form submitted successfully")
root=tk.Tk()
root.geometry("300x300")
root.title("Student Registration Form")
tk.Label(root,text="Student Name").grid(row=0)
tk.Label(root,text="Phone Number").grid(row=1)
tk.Label(root,text="Email Address").grid(row=2)
tk.Label(root,text="Residential Address").grid(row=3)
tk.Label(root,text="Gender").grid(row=4)
tk.Label(root,text="Course").grid(row=5)
tk.Label(root,text="Hobbies").grid(row=6)
name_entry=tk.Entry(root)
phone_entry=tk.Entry(root)
email_entry=tk.Entry(root)
address_text=tk.Text(root,width=20,height=5)
name_entry.grid(row=0,column=1)
phone_entry.grid(row=1,column=1)
email_entry.grid(row=2,column=1)
address_text.grid(row=3,column=1)
gender_var=tk.StringVar()
tk.Radiobutton(root,text="Male",variable=gender_var,value="Male").grid(row=4,colu
mn=1,sticky='w')
tk.Radiobutton(root,text="Female",variable=gender_var,value="Female").grid(row=4
,column=1,sticky='e')
course_var=tk.StringVar()
course_combobox=ttk.Combobox(root,textvariable=course_var)
course_combobox['values']=('BCA','BBA','BCOM')
course_combobox.grid(row=5,column=1)
hobbies={"Singing":tk.BooleanVar(),"Reading":tk.BooleanVar(),"Sports":tk.Boolean
Var()}
for idx,(hobby,var) in enumerate(hobbies.items()):
tk.Checkbutton(root,text=hobby,variable=var).grid(row=6+idx,column=1,sticky='w')
tk.Button(root,text="Submit",command=submit).grid(row=10,column=1)
root.mainloop()
OUTPUT:
try:
num=int(input("Enter a number:"))
reciprocal=1/num
print("The Reciprocal of",num,"is",reciprocal)
except(ValueError,ZeroDivisionError):
print("Invalid input! Either it's not a number or the number is zero")
finally:
print("This statement is always executed")
OUTPUT:
Enter a number:2
The Reciprocal of 2 is 0.5
This statement is always executed
Enter a number:0
Invalid input! Either it's not a number or the number is zero
This statement is always executed
Enter a number:@@
Invalid input! Either it's not a number or the number is zero
This statement is always executed
Line Chart
Bar Chart
# Create a barchart
plt.bar(courses,count,color='maroon',width=0.4)
OUTPUT:
Histogram
Piechart
#Data
languages=['Python','Java','C++','Javascript','C#']
votes=[250,150,100,75,50]
OUTPUT:
print("Min of a:",np.min(a))
print("Average of b:",np.average(b))
#Reshape array
c=a.reshape((3,1))
print("Reshaped a:",c)
#Stack arrays
print("Horizontal stack:\n",np.hstack((a,b)))
print("Vertical stack:\n",np.vstack((a,b)))
#Split array
d=np.array([[1,2,3,4],[5,6,7,8]])
print("Horizontal Split:\n",np.hsplit(d,2))
print("Vertical Split:\n",np.vsplit(d,2))
#Broadcasting
print("Broadcasting addition:\n",a+5)
OUTPUT:
Addition: [5 7 9]
Subtraction: [-3 -3 -3]
Multiplication: [ 4 10 18]
Division: [0.25 0.4 0.5 ]
a Greater than b: [False False False]
a Less than b: [ True True True]
a Equal to b: [False False False]
a Not Equal to b: [ True True True]
Logical OR: [ True True True]
Logical AND: [ True True True]
Logical NOT: [False False False]
Sum of a: 6
Max of b: 6
Min of a: 1
Average of b: 5.0
Matrix Addition:
[5 7 9]
Matrix Subtraction:
[-3 -3 -3]
Matrix Multiplication(element_wise:
[ 4 10 18]
Matrix Multiplcation:
32
Transpose of a:
[1 2 3]
Standard Deviation: 0.816496580927726
Variance: 0.6666666666666666
Median: 2.0
Reshaped a: [[1]
[2]
[3]]
Horizontal stack:
[1 2 3 4 5 6]
Vertical stack:
[[1 2 3]
[4 5 6]]
Horizontal Split:
[array([[1, 2],
[5, 6]]), array([[3, 4],
[7, 8]])]
Vertical Split:
[array([[1, 2, 3, 4]]), array([[5, 6, 7, 8]])]
Broadcasting addition:
[6 7 8]
11. Create DataFrame from Excel sheet using Pandas and Perform Operations on
DataFrames
#Slice the first two rows and select 'Student Name' and 'Age' columns
print("The first two rows of Name and Age Columns:")
print(df[:2][['Name','Age']])
#Sorting by index
df_by_index=df.sort_index(ascending =False)
print("\n DataFrame sorted by index: \n",df_by_index)
#Sorting by values
df_by_value=df.sort_values(by='Age')
print("\n DataFrame sorted by 'Age' column: \n",df_by_value)
OUTPUT:
Single Column:
0 Arun
1 Raj
2 Rani
3 Rita
4 Ashok
5 Sneha
Name: Name, dtype: object
Double columns:
Name Gender
0 Arun M
1 Raj M
2 Rani F
3 Rita F
4 Ashok M
5 Sneha F
Age 45
Gender M
Name: 0, dtype: object
Filtered DataFrame(Age>30):
Name Age Gender
0 Arun 45 M
1 Raj 43 M
5 Sneha 42 F
1 Raj 43 M
0 Arun 45 M