Python Programming Lab Programs
Python Programming Lab Programs
Part A
1. Check if a number belongs to Fibonacci sequence
def fib(n):
if n <=0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
n = int(input("Enter the number of Fibonacci Series to generate: "))
f = [fib(i) for i in range(n)]
print(f"The first {n} numbers in the Fibonacci sequence are: {f}")
check = int(input("Enter the number to be searched: "))
if check in f:
print(f"The number {check} is a Fibonacci Number.")
else:
print("The entered number {check} is not a Fibonacci Number.")
Output
Enter the number of Fibonacci Series to generate: 10
The first 10 numbers in the Fibonacci sequence are: [0, 1, 1, 2, 3, 5, 8, 13, 21,
34]
Enter the number to be searched: 8
The number 8 is a Fibonacci Number.
Output
Equation: ax^2 + bx + c
Enter a: 1
Enter b: 2
Enter c: 3
The roots are imaginary.
Equation: ax^2 + bx + c
Enter a: 1
Enter b: 5
Enter c: 3
The first root: -0.7
The second root: -4.3
(Or)
Output:
Enter a number: 8
The sum of first n natural numbers is 36
Output:
Display 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 number: 7
Number is prime
Output:
Enter number: 20
Number isn't prime
n = len(list1)
res = sequence_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Output:
Enter the element to find: 6
Element not found
if select == 1:
elif select == 2:
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == 3:
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif select == 4:
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid input")
Output:
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
Output:
UPPERCASE:
PYTHON PROGRAMMING
LOWERCASE :
python programming
Sentence case
Python Programming
Swapcase
pYThon pROGRAmmING
Title
Python programming
Original String
PytHON PrograMMing
Output:
The sorted array is: [3, 6, 9, 21, 33]
print('Initial stack')
print(stack)
Output:
Initial stack
['a', 'b', 'c']
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Part B
1. Demonstrate usage of basic regular expressions.
import re
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())
x = re.split("\s", txt)
print(x)
x = re.search("ai", txt)
print(x) #this will print an object
Output
['ai', 'ai']
The first white-space character is located in position: 3
['The', 'rain', 'in', 'Spain']
The9rain9in9Spain
<re.Match object; span=(5, 7), match='ai'>
# Password Validation
def validate_password(password):
pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-
z\d@$!%*?&]{8,}$"
if re.match(pattern, password):
return True
return False
Output
Email Validation: True
Password Validation: True
Phone Number Validation: True
# 1. Accessing elements
print("First element:", my_list[0])
print("Last element:", my_list[-1])
# 2. Slicing a list
print("Sliced List (2nd to 4th elements):", my_list[1:4])
# 3. Adding elements
my_list.append(60)
print("List after appending 60:", my_list)
my_list.insert(2, 25)
print("List after inserting 25 at index 2:", my_list)
# 4. Removing elements
my_list.remove(30)
print("List after removing 30:", my_list)
# 5. Finding elements
index_of_40 = my_list.index(40)
print("Index of 40:", index_of_40)
count_of_40 = my_list.count(40)
print("Count of 40 in list:", count_of_40)
# 6. List concatenation
new_list = my_list + [70, 80, 90]
print("Concatenated List:", new_list)
# 7. Repeating elements
repeated_list = my_list * 2
print("Repeated List:", repeated_list)
# 8. Sorting a list
my_list.sort()
print("Sorted List:", my_list)
my_list.sort(reverse=True)
print("List sorted in descending order:", my_list)
# 9. Reversing a list
my_list.reverse()
print("Reversed List:", my_list)
Output
Original List: [10, 20, 30, 40, 50]
First element: 10
Last element: 50
Sliced List (2nd to 4th elements): [20, 30, 40]
List after appending 60: [10, 20, 30, 40, 50, 60]
List after inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60]
List after removing 30: [10, 20, 25, 40, 50, 60]
List after popping last element: [10, 20, 25, 40, 50]
Popped element: 60
List after deleting element at index 1: [10, 25, 40, 50]
Index of 40: 2
Count of 40 in list: 1
Concatenated List: [10, 25, 40, 50, 70, 80, 90]
Repeated List: [10, 25, 40, 50, 10, 25, 40, 50]
Sorted List: [10, 25, 40, 50]
List sorted in descending order: [50, 40, 25, 10]
Reversed List: [10, 25, 40, 50]
List after clearing all elements: []
After adding email: {'name': 'Alice', 'age': 30, 'city': 'New York', 'email':
'alice@example.com'}
After modifying age: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email':
'alice@example.com'}
import sqlite3
try:
# Handle errors
except sqlite3.Error as error:
print('Error occurred - ', error)
if sqliteConnection:
sqliteConnection.close()
print('SQLite Connection closed')
Output:
conn = sqlite3.connect('RK.db')
# Creating a cursor object using the
# cursor() method
cursor = conn.cursor()
# Queries to INSERT records.
cursor.execute('''INSERT INTO STUDENT VALUES ('KAVYA','K','B',35)''')
# Display data inserted
print("Data Inserted in the table: ")
data=cursor.execute(''' select * from STUDENT''')
for row in data:
print(row)
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
Output:
l2.place(x=80,y=130)
name=Entry(ws)
name.place(x=240,y=130) #creating email id text box
labl_2 = Label(ws, text="Email",width=20,font=("bold", 10))
labl_2.place(x=68,y=180)
entry_02 = Entry(ws)
entry_02.place(x=240,y=180)
#creating a checkbox for gender var1=IntVar()
labl_3 = Label(ws, text="Gender",width=20,font=("bold", 10))
labl_3.place(x=70,y=230)
var1=IntVar()
Checkbutton(ws,text="Male",variable=var1).place(x=235,y=230)
var2=IntVar()
Checkbutton(ws,text="Female",variable=var2).place(x=290,y=230)
defsubmit():
return Label(ws, text="Registration successfull").pack()
submitBtn=Button(ws,
text='Submit',width=20,bg='brown',fg='white',command=submit).place(x=180,y=
380)
ws.mainloop()
Output:
plt.legend(["Line"])
plt.show()
Output:
Bar Chart:
import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3, 12, 2, 4, 4]
y = [3, 2, 1, 4, 5, 6, 7]
# This will plot a simple bar chart
plt.bar(x, y)
# Title to the plot
plt.title("Bar Chart")
# Adding the legends
plt.legend(["bar"])
plt.show()
Output :
Pie Chart:
importmatplotlib.pyplotasplt
# data to display on plots
x=[1,2,3,4]
Output:
11. Create Data Frame from Excel sheet using Pandas and Perform
Operations on Data Frames.
import pandas as pd
df = pd.read_excel('C:/Users/bella/OneDrive/Desktop/BATCH-4/BCA.xlsx')
print(df)
Output:
Head&tail
import pandas as pd
df = pd.read_excel('C:/Users/bella/OneDrive/Desktop/BATCH-4/BCA.xlsx')
print(df.head())
print(df.tail())
Output:
Sorting
import pandas as pd
df = pd.read_excel('C:/Users/bella/OneDrive/Desktop/BATCH-4/BCA.xlsx')
sorted_column = df.sort_values(['Campus ID'], ascending = True)
print(sorted_column.head(5))
Output: