PYTHON LAB PROGRAMS:
1. Check if a number belongs to the Fibonacci sequence
print("Enter a number")
n = int(input())
f1, f2 = 0, 1
flag = 0
if n == 0 or n == 1:
flag = 1
else:
while f2 <= n:
f3 = f1 + f2
if n == f3:
flag = 1
break
f1, f2 = f2, f3
if flag == 1:
print("Fibonacci")
else:
print("Not Fibonacci")
2. Solve Quadratic Equation.
import math
print("Enter values for a, b, and c:")
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))
d = (b * b) - (4 * a * c)
if d < 0:
print("Roots are imaginary.")
elif d == 0:
print("Roots are equal.")
x = -b / (2 * a)
print("Solution =", x)
else:
print("Roots are real and distinct.")
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b - math.sqrt(d)) / (2 * a)
print("Solution 1 =", x1)
print("Solution 2 =", x2)
3.Find the sum of natural numbers.
print("enter number")
n=int(input())
i=1
total=0
while i <= n:
total =total +i
i=i+1
print("sum of natural numbers=",total)
4. Display multiplication tables.
print("enter number")
n=int(input())
i=1
while i<=10:
print(n,"*",i, "=",(n*i))
i=i+1
5. check if a given number is a prime number or not.
print("Enter a number")
n = int(input())
flag = 0
i=2
if n <= 1:
flag = 1
while i < n:
if n % i == 0:
flag = 1
break
i=i+1
if flag == 0:
print("Prime number")
else:
print("Not a prime number")
6. Implement a sequential search.
def lsearch(lst, n, key):
i=0
while i < n:
if key == lst[i]:
return i + 1 # Returning position (1-based)
i += 1
return -1
print("Enter number of elements:")
n = int(input())
lst = []
print("Enter elements:")
for i in range(n):
ele = input()
lst.append(ele)
print("Enter key element to search:")
key = input()
flag = lsearch(lst, n, key)
if flag == -1:
print("Key element NOT FOUND.")
else:
print("Key element FOUND at position:", flag)
7. Create a simple calculator program.
print("Enter 2 numbers:")
a = int(input())
b = int(input())
print("Enter operator (+, -, *, %):")
opr = input()
if opr == '+':
print(a, "+", b, "=", a + b)
elif opr == '-':
print(a, "-", b, "=", a - b)
elif opr == '*':
print(a, "*", b, "=", a * b)
elif opr == '%':
print(a, "%", b, "=", a % b)
else:
print("Invalid operator")
8.Explore string Functions.
print("Enter a string:")
str = input()
print("Given string =", str)
print("Length of given string =", len(str))
print("Lower case conversion =", str.lower())
print("Upper case conversion =", str.upper())
print("Capitalization of string =", str.capitalize())
print("Given string is digit:", str.isdigit())
print("Given string is alphabetic:", str.isalpha())
print("Given string is alphanumeric:", str.isalnum())
9.Implement Selection sort.
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
# Swap the found minimum with the first element
arr[i], arr[min_index] = arr[min_index], arr[i]
arr = []
n = int(input("Enter number of elements: "))
print("Enter the elements:")
for _ in range(n):
num = int(input())
arr.append(num)
selection_sort(arr)
print("Sorted array:", arr)
10.Implement Stack.
stack = []
def Push():
print("Enter element to Push:")
ele = input()
stack.append(ele)
def Pop():
if len(stack) == 0:
print("Stack is underflow")
else:
print("Popped element =", stack.pop())
def Display():
if len(stack) == 0:
print("Stack is underflow")
else:
print(stack, ":top")
while (1):
print("1. Push\n2. Pop\n3. Display\n4. Exit")
n = int(input("Enter your choice: "))
if n == 1:
Push()
elif n == 2:
Pop()
elif n == 3:
Display()
elif n == 4:
break
else:
print("Invalid input")
11.Read and Write into a file
print("Enter data to insert into file:")
str = input()
# Write to file
filePtr = open("d:\\abc.txt", "w")
filePtr.write(str)
filePtr.close()
filePtr = open("d:\\abc.txt", "r")
str = filePtr.read()
print("Entered data = ", str)
filePtr.close()
print()
PART B
1.Demonstrate usage on basic regular expression.
import re
s = "Today is the wonderful day"
print(s)
print("Enter text to match:")
str1 = input()
x = re.findall(str1, s)
if x:
print("Given text is MATCHED")
else:
print("Given text is NOT MATCHED")
2. Demonstrate use of advanced regular expressions for
data validation.
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.fullmatch(pattern, email)
def validate_phone(phone):
pattern = r'^[6-9]\d{9}$'
return re.fullmatch(pattern, phone)
def validate_password(password):
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$'
return re.fullmatch(pattern, password)
def validate_date(date):
pattern = r'^(0[1-9]|[12][0-9]|3[01])[-/](0[1-9]|1[012])[-
/](19|20)\d\d$'
return re.fullmatch(pattern, date)
def validate_ip(ip):
pattern = r'^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-
5]|2[0-4]\d|1\d\d|[1-9]?\d)$'
return re.fullmatch(pattern, ip)
data_samples = {
"Email": "example.user123@gmail.com",
"Phone": "9876543210",
"Password": "Strong@123",
"Date": "06-06-2025",
"IP": "192.168.1.1"
}
print("Validation Results:")
print("Email valid:", bool(validate_email(data_samples["Email"])))
print("Phone valid:", bool(validate_phone(data_samples["Phone"])))
print("Password valid:",
bool(validate_password(data_samples["Password"])))
print("Date valid:", bool(validate_date(data_samples["Date"])))
print("IP address valid:", bool(validate_ip(data_samples["IP"])))
3.Demonstrate use of list.
my_list = [50, 40, 10, 20, 30]
print("List =", my_list)
print("Length of list =", len(my_list))
print("Sum of all the elements =", sum(my_list))
print("Minimum element =", min(my_list))
print("Maximum element =", max(my_list))
print("Sorted list =", sorted(my_list))
my_list.append(60)
print("After adding another element =", my_list)
my_list.remove(40)
print("After removing an element =", my_list)
4. Demonstrate use of dictionary.
dict = {1: 60, 2: 70, 3: 100, 40: 90, 5: 300, 6: 40, 7: 50}
print("dictionary elements are :",dict)
print("length of elements are :",len(dict))
dict.update({1:5})
print("after update dictionary ,dict2=",dict)
dict2= dict.copy()
print("after copy dictionary ,dict2=",dict2)
dict.pop(3)
print("after removing an element=",dict)
print("after sorted dictionary elements=",sorted (dict))
dict.clear()
print("after clear dictionary=",dict)
5.Create SQLite Database and perform operation on tables.
import sqlite3
conn = sqlite3.connect('vvvqc.db')
conn.execute('''CREATE TABLE IF NOT EXISTS EMPLOYEE (
ID INT NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL);''')
print("Table created")
conn.execute("INSERT INTO EMPLOYEE (ID, NAME, AGE) VALUES (1,
'Raju', 32);")
conn.execute("INSERT INTO EMPLOYEE (ID, NAME, AGE) VALUES (2,
'Ajay', 30);")
print("Records Inserted")
cursor = conn.execute("SELECT ID, NAME, AGE FROM EMPLOYEE")
for row in cursor:
print("ID =", row[0])
print("NAME =", row[1])
print("AGE =", row[2])
print("---------------")
conn.commit()
conn.close()
6. create a GUI using Tkinter module.
from tkinter import *
top = Tk()
top.geometry("400x250") # Set window size
Label(top, text="Name").place(x=30, y=50)
Label(top, text="Email").place(x=30, y=90)
Label(top, text="Password").place(x=30, y=130)
e1 = Entry(top)
e1.place(x=80, y=50)
e2 = Entry(top)
e2.place(x=80, y=90)
e3 = Entry(top, show='*')
e3.place(x=95, y=130)
# Add Buttonsubmit = Button(top, text="Submit")
submit.place(x=110, y=160)
top.mainloop()
7. Demonstrate exceptions in python.
print("enter 2 nos")
a=int(input())
b=int(input())
try:
div=a/b
except:
print("you are trying to divide a number by zero")
else:
print("division =",div)
finally:
print("this is division of 2 number program")
8. Drawing Line chart and bar chart using Matplotlib.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([2, 4, 6, 8, 10])
y = np.array([2, 4, 6, 8, 10])
plt.plot(x, y, marker='o')
plt.title("Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
import matplotlib.pyplot as plt
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23, 17, 35, 29, 12]
plt.bar(langs, students, color='skyblue')
plt.title("Students in Programming Languages")
plt.xlabel("Languages")
plt.ylabel("Number of Students")
plt.show()
9. Drawing Histogram and pie chart using Matplotlib.
import matplotlib.pyplot as plt
marks = [45, 67, 89, 70, 56, 90, 78, 88, 55, 60]
bins = [40, 50, 60, 70, 80, 90, 100]
plt.figure(1)
plt.hist(marks, bins, color='skyblue', edgecolor='black')
plt.title("Student Marks Histogram")
plt.xlabel("Marks Range")
plt.ylabel("Number of Students")
subjects = ['Math', 'Physics', 'Chemistry', 'Biology']
scores = [80, 70, 60, 90]
colors = ['gold', 'lightgreen', 'lightcoral', 'lightskyblue']
plt.figure(2)
plt.pie(scores, labels=subjects, colors=colors, autopct='%1.1f%%',
startangle=140)
plt.title("Subject-wise Score Distribution")
plt.axis('equal') # Makes the pie a circle
plt.show()
10.create array using Numpy and perform operation on array.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Array elements are:\n", arr)
print("Number of dimensions:", arr.ndim)
x = np.arange(12)
y = np.reshape(x, (4, 3))
print("One dimensional array:", x)
print("Converted to 2D:\n", y)
s = slice(2, 7, 2)
print("After slicing:", x[s])
11.create data frame from excel sheet using pandas and
perform operation on data frames.
import pandas as pd
df1 = pd.DataFrame({
'name': ['AAA', 'BBB', 'CCC', 'DDD', 'EEE'],
'age': [10, 20, 30, 40, 50]
})
df2 = pd.DataFrame({
'name': ['FFF', 'GGG', 'HHH', 'III', 'JJJ'],
'age': [15, 25, 35, 45, 55]
})
with pd.ExcelWriter('sample.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet2', index=False)
df1 = pd.read_excel('sample.xlsx', sheet_name='Sheet1')
df2 = pd.read_excel('sample.xlsx', sheet_name='Sheet2')
print(df1)
print(df2)