Course Title: Python Programming Lab(21BCA4C10PPP)
Sl.No. Name of the Program Page No Remarks
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
Demonstrate use of advanced regular expressions for data
2.
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 modul
7. Demonstrate Exceptions in Python
8. Drawing Line chart and Bar chart using Matplotlib
9. Drawing Histogram and Pie chart using Matplotlib
Create Array using NumPy and Perform Operations on
10.
Array
Create DataFrame from Excel sheet using Pandas and
11.
Perform Operations on DataFrames
1
1. Check if a number belongs to the Fibonacci Sequence
num = int(input("Enter a number: "))
if num == 0 or num == 1:
print(f"{num} is a Fibonacci number.")
else:
a=0
b=1
while b < num:
temp = b # Store the current value of b
b = a + b # Calculate the next Fibonacci number
a = temp # Update a to the old value of b
if b == num:
print(f"{num} is a Fibonacci number.")
else:
print(f"{num} is not a Fibonacci number.")
# Output:
Enter a number: 8
8 is a Fibonacci number.
2
2. Solve Quadratic Equations
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
D=b*b-4*a*c
if D > 0:
root1 = (-b + (D ** 0.5)) / (2 * a)
root2 = (-b - (D ** 0.5)) / (2 * a)
print("Two real roots:", root1, "and", root2)
elif D == 0:
root1 = -b / (2 * a)
print("One real root:", root1)
else:
print("No real roots")
Output:
Example 1 (Two Real Roots)
Enter coefficient a: 1
Enter coefficient b: -3
Enter coefficient c: 2
Two real roots: 2.0 and 1.0
Example 2 (One Real Root)
Enter coefficient a: 1
Enter coefficient b: -2
Enter coefficient c: 1
One real root: 1.0
Example 3 (No Real Roots)
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
No real roots
3
3. Find the sum of n natural numbers
n = int(input("Enter a number: "))
sum_n = (n * (n + 1)) // 2
print("The sum of first", n, "natural numbers is:", sum_n)
Output:
Example 1:
Enter a number: 5
The sum of first 5 natural numbers is: 15
Example 2:
Enter a number: 10
The sum of first 10 natural numbers is: 55
Example 3:
Enter a number: 100
The sum of first 100 natural numbers is: 5050
4
4. Display Multiplication Tables
n = int(input("Enter a number: "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)
Output:
Enter a number: 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
5
5. Check if a given number is a Prime Number or not
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
# Output :
Enter a number: 7
7 is a prime number
6
6. Implement a sequential search
numbers = [10, 20, 30, 40, 50]
search_element = 30
result = -1
for index in range(len(numbers)):
if numbers[index] == search_element:
result = index
break
if result != -1:
print(f"Element {search_element} found at index {result}")
else:
print(f"Element {search_element} not found")
Output:
Element 30 found at index 2
7
7. Create a calculator program
print("Choose an operation:")
print("1. Addition (+)\n2. Subtraction (-)\n3. Multiplication (*)\n4. Division (/)")
choice = input("Enter operation number (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result:", num1 + num2)
elif choice == '2':
print("Result:", num1 - num2)
elif choice == '3':
print("Result:", num1 * num2)
elif choice == '4':
print("Result:", num1 / num2 if num2 != 0 else "Error: Division by zero")
else:
print("Invalid input!")
Output:
Choose an operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter operation number (1/2/3/4): 1
Enter first number: 25
Enter second number: 20
Result: 45.0
8
8. Explore string functions
text = " Hello, Python World! "
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
print("Stripped:", text.strip())
print("Index of 'Python':", text.find("Python"))
print("Replace 'World' with 'Universe':", text.replace("World", "Universe"))
print("Split words:", text.split())
print("Starts with 'Hello':", text.strip().startswith("Hello"))
print("Ends with 'World!':", text.strip().endswith("World!"))
print("Count of 'o':", text.count("o"))
print("Swap case:", text.swapcase())
Output:
Uppercase: HELLO, PYTHON WORLD!
Lowercase: hello, python world!
Stripped: Hello, Python World!
Index of 'Python': 9
Replace 'World' with 'Universe': Hello, Python Universe!
Split words: ['Hello,', 'Python', 'World!']
Starts with 'Hello': True
Ends with 'World!': True
Count of 'o': 3
Swap case: hELLO, pYTHON wORLD!
9
9. Implement Selection Sort
numbers = [64, 25, 12, 22, 11]
for i in range(len(numbers)):
min_index = i
for j in range(i + 1, len(numbers)):
if numbers[j] < numbers[min_index]:
min_index = j
numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
print("Sorted List:", numbers)
Output:
Sorted List: [11, 12, 22, 25, 64]
10
10. Implement Stack
stack = []
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack after pushing elements:", stack)
popped_element = stack.pop()
print("Popped Element:", popped_element)
print("Stack after popping an element:", stack)
Output:
Stack after pushing elements: [10, 20, 30]
Popped Element: 30
Stack after popping an element: [10, 20]
11
11. Read and write into a file
file = open("example.txt", "w")
file.write("Hello, Technocrat!\n")
file.close()
print("Data written to file successfully.")
file = open("example.txt", "r")
print("\nFile Content:\n", file.read())
file.close()
Output:
Data written to file successfully.
File Content:
Hello, Technocrat!
12
PART-B
13
1. Demonstrate usage of basic regular expression
import re
text = "My email is [email protected] and I use it frequently."
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
match = re.search(pattern, text)
if match:
print("Found email:", match.group())
else:
print("No email found")
Output:
14
2. Demonstrate use of advanced regular expressions for data validation.
import re
email = "[email protected]"
phone = "+91 9876543210"
password = "Strong@123"
email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
phone_pattern = r"^\+?[0-9]{1,3}[-\s]?[0-9]{10}$"
password_pattern = r"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
email_valid = bool(re.match(email_pattern, email))
phone_valid = bool(re.match(phone_pattern, phone))
password_valid = bool(re.match(password_pattern, password))
print("Email Valid:", email_valid)
print("Phone Number Valid:", phone_valid)
print("Password Valid:", password_valid)
Output:
Email Valid: True
Phone Number Valid: True
Password Valid: True
15
3. Demonstrate use of List
fruits = ["apple", "banana", "cherry", "mango"]
print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])
fruits.append("orange")
print("After adding orange:", fruits)
fruits.insert(2, "grape")
print("After inserting grape at index 2:", fruits)
fruits[1] = "blueberry"
print("After updating second fruit:", fruits)
fruits.remove("cherry")
print("After removing cherry:", fruits)
print("All fruits in the list:")
for fruit in fruits:
print("-", fruit)
print("Total number of fruits:", len(fruits))
Output:
First fruit: apple
Last fruit: mango
After adding orange: ['apple', 'banana', 'cherry', 'mango', 'orange']
After inserting grape at index 2: ['apple', 'banana', 'grape', 'cherry', 'mango', 'orange']
After updating second fruit: ['apple', 'blueberry', 'grape', 'cherry', 'mango', 'orange']
After removing cherry: ['apple', 'blueberry', 'grape', 'mango', 'orange']
All fruits in the list:
- apple
- blueberry
- grape
- mango
- orange
Total number of fruits: 5
16
4. Demonstrate use of Dictionaries
student = {
"name": "Techman",
"age": 21,
"course": "Python Programming",
"is_enrolled": True
}
print("Name:", student["name"])
print("Course:", student["course"])
student["grade"] = "A"
print("After adding grade:", student)
student["age"] = 22
print("After updating age:", student)
del student["is_enrolled"]
print("After removing is_enrolled:", student)
print("Student Details:")
for key, value in student.items():
print(f"{key} => {value}")
if "name" in student:
print("The 'name' key exists in the dictionary.")
Output:
Name: Techman
Course: Python Programming
After adding grade: {'name': 'Techman', 'age': 21, 'course': 'Python Programming', 'is_enrolled': True, 'grade': 'A'}
After updating age: {'name': 'Techman', 'age': 22, 'course': 'Python Programming', 'is_enrolled': True, 'grade': 'A'}
After removing is_enrolled: {'name': 'Techman', 'age': 22, 'course': 'Python Programming', 'grade': 'A'}
Student Details:
name => Techman
age => 22
course => Python Programming
grade => A
The 'name' key exists in the dictionary.
17
5. Create SQLite Database and Perform Operations on Tables
import sqlite3
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS student (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
course TEXT
)
''')
print("Table created successfully.")
cursor.execute("INSERT INTO student (name, age, course) VALUES (?, ?, ?)", ("Techman", 21, "Python"))
cursor.execute("INSERT INTO student (name, age, course) VALUES (?, ?, ?)", ("Alice", 22, "Data Science"))
cursor.execute("INSERT INTO student (name, age, course) VALUES (?, ?, ?)", ("Bob", 23, "AI"))
conn.commit()
print("Data inserted successfully.")
cursor.execute("SELECT * FROM student")
rows = cursor.fetchall()
print("\nAll Students:")
for row in rows:
print(row)
cursor.execute("UPDATE student SET course = ? WHERE name = ?", ("Machine Learning", "Alice"))
conn.commit()
print("\nUpdated Alice's course.")
cursor.execute("DELETE FROM student WHERE name = ?", ("Bob",))
conn.commit()
print("Deleted Bob's record.")
18
cursor.execute("SELECT * FROM student")
final_rows = cursor.fetchall()
print("\nFinal Students List:")
for row in final_rows:
print(row)
conn.close()
Output:
Table created successfully.
Data inserted successfully.
All Students:
(1, 'Techman', 21, 'Python')
(2, 'Alice', 22, 'Machine Learning')
(4, 'Techman', 21, 'Python')
(5, 'Alice', 22, 'Data Science')
(6, 'Bob', 23, 'AI')
Updated Alice's course.
Deleted Bob's record.
Final Students List:
(1, 'Techman', 21, 'Python')
(2, 'Alice', 22, 'Machine Learning')
(4, 'Techman', 21, 'Python')
(5, 'Alice', 22, 'Machine Learning')
19
6. Create a GUI using Tkinter module
import tkinter as tk
from tkinter import messagebox
def show_name():
name = name_entry.get()
if name:
output_label.config(text=f"Hello, {name}!")
else:
messagebox.showwarning("Input Error", "Please enter your name.")
root = tk.Tk()
root.title("Welcome App")
root.geometry("300x200") # width x height
name_label = tk.Label(root, text="Enter your name:")
name_label.pack(pady=10)
name_entry = tk.Entry(root)
name_entry.pack()
submit_button = tk.Button(root, text="Submit", command=show_name)
submit_button.pack(pady=10)
output_label = tk.Label(root, text="", fg="blue")
output_label.pack()
root.mainloop()
Output:
20
7. Demonstrate Exceptions in Python
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except TypeError:
print("Error: Both inputs must be numbers.")
else:
print("Result:", result)
finally:
print("This block always executes (cleanup or final steps).")
print("Case 1: Normal Division")
divide_numbers(10, 2)
print("\nCase 2: Division by Zero")
divide_numbers(10, 0)
print("\nCase 3: Invalid Input (String)")
divide_numbers(10, "five")
Output:
Case 1: Normal Division
Result: 5.0
This block always executes (cleanup or final steps).
Case 2: Division by Zero
Error: Cannot divide by zero.
This block always executes (cleanup or final steps).
Case 3: Invalid Input (String)
Error: Both inputs must be numbers.
This block always executes (cleanup or final steps).
21
8. Drawing Line chart and Bar chart using Matplotlib
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [100, 120, 90, 140, 110]
plt.figure(figsize=(8, 4))
plt.plot(months, sales, marker='o', color='blue', label='Sales')
plt.title("Monthly Sales - Line Chart")
plt.xlabel("Months")
plt.ylabel("Sales ($)")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
plt.figure(figsize=(8, 4))
plt.bar(months, sales, color='green', label='Sales')
plt.title("Monthly Sales - Bar Chart")
plt.xlabel("Months")
plt.ylabel("Sales ($)")
plt.legend()
plt.tight_layout()
plt.show()
Output:
LINE CHART BAR CHART
22
9. Drawing Histogram and Pie chart using Matplotlib
import matplotlib.pyplot as plt
ages = [18, 22, 25, 30, 22, 35, 40, 42, 25, 26, 28, 30, 22, 35, 38, 40, 50, 55, 60]
plt.figure(figsize=(8, 4))
plt.hist(ages, bins=7, color='skyblue', edgecolor='black')
plt.title("Age Distribution - Histogram")
plt.xlabel("Age Groups")
plt.ylabel("Number of People")
plt.grid(True)
plt.tight_layout()
plt.show()
# Sample data: Market share of brands
brands = ['Brand A', 'Brand B', 'Brand C', 'Brand D']
market_share = [30, 25, 25, 20]
plt.figure(figsize=(6, 6))
plt.pie(market_share, labels=brands, autopct='%1.1f%%', startangle=140, colors=['gold',
'lightgreen', 'lightcoral', 'lightskyblue'])
plt.title("Market Share - Pie Chart")
plt.axis('equal')
plt.tight_layout()
plt.show()
Output:
HISTOGRAM PIE CHART
23
10.Create Array using NumPy and Perform Operations on Array
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50])
arr2 = np.array([1, 2, 3, 4, 5])
print("Array 1:", arr1)
print("Array 2:", arr2)
print("\nAddition:", arr1 + arr2)
print("Subtraction:", arr1 - arr2)
print("Multiplication:", arr1 * arr2)
print("Division:", arr1 / arr2)
print("\nShape of arr1:", arr1.shape)
print("Data type of arr1:", arr1.dtype)
print("\nFirst Element of arr1:", arr1[0])
print("Last 3 Elements of arr1:", arr1[-3:])
print("\nSum of arr1:", np.sum(arr1))
print("Mean of arr1:", np.mean(arr1))
print("Max of arr1:", np.max(arr1))
matrix = np.array([[1, 2], [3, 4]])
print("\n2D Array:\n", matrix)
print("Transpose:\n", matrix.T)
Output:
Array 1: [10 20 30 40 50]
Array 2: [1 2 3 4 5]
Addition: [11 22 33 44 55]
Subtraction: [ 9 18 27 36 45]
Multiplication: [ 10 40 90 160 250]
Division: [10. 10. 10. 10. 10.]
Shape of arr1: (5,)
Data type of arr1: int64
First Element of arr1: 10
Last 3 Elements of arr1: [30 40 50]
Sum of arr1: 150
Mean of arr1: 30.0
Max of arr1: 50
2D Array:
[[1 2]
[3 4]]
Transpose:
[[1 3]
[2 4]]
24
11. Create DataFrame from Excel sheet using Pandas and Perform Operations on DataFrames
import pandas as pd
df = pd.read_excel("C:/Users/manju/OneDrive/Desktop/sample.xlsx")
print(" Excel file loaded successfully!\n")
print(" First 5 rows:")
print(df.head())
Note: - Please use this link to download the excel file used in
this program and execute the program using Jupyter
print("\n DataFrame Info:") Notebook, it will also work in ‘IDLE’ and ‘Thonny’ as well
print(df.info()) To download: - press click on link below’ save the file in .xlsx
format, save file on desktop and then ‘copy as path’ and
paste in df = pd.read_excel(“C:/xxxxx/xxxxx/xxxx.xlsx”)
print("\n Statistical Summary:")
print(df.describe()) https://docs.google.com/spreadsheets/d/1ajVH3ApxcO1dep
O0Pq5l6LAwRbwmkHwZ/edit?usp=sharing&ouid=118027155
565520059752&rtpof=true&sd=true
print("\n Column Names:")
print(df.columns)
if 'Age' in df.columns:
print("\n Rows where Age > 25:")
print(df[df['Age'] > 25])
else:
print("\n No 'Age' column found for filtering.")
if 'Department' in df.columns:
print("\n Grouped by Department:")
print(df.groupby('Department').size())
else:
print("\n No 'Department' column found for grouping.")
Output:
Excel file loaded successfully!
First 5 rows:
ID Name Age Department Salary
0 1 Alice 28 HR 45000
1 2 Bob 35 IT 60000
2 3 Charlie 22 Marketing 38000
3 4 David 29 IT 55000
4 5 Eva 41 Finance 70000
DataFrame Info:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
25
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 8 non-null int64
1 Name 8 non-null object
2 Age 8 non-null int64
3 Department 8 non-null object
4 Salary 8 non-null int64
dtypes: int64(3), object(2)
memory usage: 448.0+ bytes
None
Statistical Summary:
ID Age Salary
count 8.00000 8.000000 8.000000
mean 4.50000 29.500000 51000.000000
std 2.44949 6.164414 10419.761445
min 1.00000 22.000000 38000.000000
25% 2.75000 25.500000 44250.000000
50% 4.50000 28.500000 49000.000000
75% 6.25000 32.000000 56250.000000
max 8.00000 41.000000 70000.000000
Column Names:
Index(['ID', 'Name', 'Age', 'Department', 'Salary'], dtype='object')
Rows where Age > 25:
ID Name Age Department Salary
0 1 Alice 28 HR 45000
1 2 Bob 35 IT 60000
3 4 David 29 IT 55000
4 5 Eva 41 Finance 70000
5 6 Frank 26 Marketing 42000
6 7 Grace 31 HR 47000
Grouped by Department:
Department
Finance 2
HR 2
IT 2
Marketing 2
dtype: int64
26