Code – 1
1. Personalized Greeting Generator
name = input("Enter your name: ")
print(f"Hello, {name}! Welcome!")
-----------------------
2. Calculating Areas of Geometric Figures
shape = input("Enter the shape (circle, rectangle, triangle): ").lower()
if shape == "circle":
radius = float(input("Enter the radius: "))
area = 3.14 * radius ** 2
print(f"Area of the circle: {area}")
elif shape == "rectangle":
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
area = length * width
print(f"Area of the rectangle: {area}")
elif shape == "triangle":
base = float(input("Enter the base: "))
height = float(input("Enter the height: "))
area = 0.5 * base * height
print(f"Area of the triangle: {area}")
else:
print("Invalid shape!")
---------------
3. Developing Conversion Utilities
conversion_type = input("Enter conversion type (rupees_to_dollars,
celsius_to_fahrenheit, inches_to_feet): ").lower()
if conversion_type == "rupees_to_dollars":
rupees = float(input("Enter amount in Rupees: "))
dollars = rupees / 75
print(f"{rupees} Rupees is {dollars} Dollars.")
elif conversion_type == "celsius_to_fahrenheit":
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius} Celsius is {fahrenheit} Fahrenheit.")
elif conversion_type == "inches_to_feet":
inches = float(input("Enter length in inches: "))
feet = inches / 12
print(f"{inches} inches is {feet} feet.")
else:
print("Invalid conversion type!")
----------------------------------
4. Calculating Gross Salary of an Employee
basic_salary = float(input("Enter the basic salary: "))
da = 0.70 * basic_salary
ta = 0.30 * basic_salary
hra = 0.10 * basic_salary
gross_salary = basic_salary + da + ta + hra
print(f"The gross salary is: {gross_salary}")
----------------------------
5. Calculating Simple Interest
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period in years: "))
simple_interest = (principal * rate * time) / 100
print(f"The simple interest is: {simple_interest}")
--------------------------
6. Exploring Basic Arithmetic Operations in Python
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print(f"Addition: {num1 + num2}")
print(f"Subtraction: {num1 - num2}")
print(f"Multiplication: {num1 * num2}")
print(f"Division: {num1 / num2 if num2 != 0 else 'undefined'}")
print(f"Modulus: {num1 % num2 if num2 != 0 else 'undefined'}")
code -2
1. Task List Manager (Using Lists and Tuples)
class TaskManager:
def __init__(self):
self.tasks = []
def add_task(self, task):
self.tasks.append(task)
print(f"Task '{task}' added successfully.")
def remove_task(self, task):
if task in self.tasks:
self.tasks.remove(task)
print(f"Task '{task}' removed successfully.")
else:
print("Task not found!")
def update_task(self, old_task, new_task):
if old_task in self.tasks:
index = self.tasks.index(old_task)
self.tasks[index] = new_task
print(f"Task '{old_task}' updated to '{new_task}'.")
else:
print("Task not found!")
def show_tasks(self):
if self.tasks:
print("Task List:")
for i, task in enumerate(sorted(self.tasks), 1):
print(f"{i}. {task}")
else:
print("No tasks available.")
# Example usage
manager = TaskManager()
manager.add_task("Complete Python assignment")
manager.add_task("Read a cryptography book")
manager.show_tasks()
manager.update_task("Read a cryptography book", "Read a machine
learning book")
manager.remove_task("Complete Python assignment")
manager.show_tasks()
------------------------------------
2. Student Enrollment Manager (Using Sets and Set Operations)
class StudentEnrollment:
def __init__(self):
self.courses = {
"CET": set(),
"JEE": set(),
"NEET": set()
def enroll_student(self, name, exam):
if exam in self.courses:
self.courses[exam].add(name)
print(f"{name} enrolled in {exam} successfully.")
else:
print("Invalid exam name!")
def show_students(self, exam):
if exam in self.courses:
print(f"Students enrolled in {exam}: {self.courses[exam]}")
else:
print("Invalid exam name!")
def show_common_students(self, exam1, exam2):
if exam1 in self.courses and exam2 in self.courses:
common = self.courses[exam1].intersection(self.courses[exam2])
print(f"Students appearing for both {exam1} and {exam2}:
{common}")
else:
print("Invalid exam names!")
def show_all_students(self):
all_students = self.courses["CET"].union(self.courses["JEE"],
self.courses["NEET"])
print(f"All enrolled students: {all_students}")
# Example usage
manager = StudentEnrollment()
manager.enroll_student("Alice", "CET")
manager.enroll_student("Bob", "JEE")
manager.enroll_student("Charlie", "CET")
manager.enroll_student("Alice", "JEE")
manager.show_students("CET")
manager.show_common_students("CET", "JEE")
manager.show_all_students()
------------------------------------
3. Student Record Keeper (Using Dictionaries)
class StudentRecord:
def __init__(self):
self.records = {}
def add_student(self, name, grades, attendance):
self.records[name] = {"Grades": grades, "Attendance": attendance}
print(f"Student {name} added successfully.")
def update_grades(self, name, new_grades):
if name in self.records:
self.records[name]["Grades"] = new_grades
print(f"Updated grades for {name}.")
else:
print("Student not found!")
def update_attendance(self, name, new_attendance):
if name in self.records:
self.records[name]["Attendance"] = new_attendance
print(f"Updated attendance for {name}.")
else:
print("Student not found!")
def show_student(self, name):
if name in self.records:
print(f"Record for {name}: {self.records[name]}")
else:
print("Student not found!")
def show_all_students(self):
if self.records:
for name, data in self.records.items():
print(f"{name}: Grades: {data['Grades']}, Attendance:
{data['Attendance']}%")
else:
print("No student records available.")
# Example usage
record = StudentRecord()
record.add_student("Alice", [85, 90, 88], 95)
record.add_student("Bob", [78, 82, 80], 88)
record.show_all_students()
record.update_grades("Alice", [90, 92, 89])
record.update_attendance("Bob", 92)
record.show_student("Alice")
Code – 3
### 1. Triangle Pattern Generator
This prints a right-angled triangle pattern using loops.
```python
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
print("*" * i)
```
---
### 2. Number Type Identifier (Even or Odd)
This program checks whether a number is even or odd.
```python
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
```
---
### 3. Character Type Identifier
This determines if the input is a digit, lowercase, uppercase, or special
character.
```python
char = input("Enter a character: ")
if char.isdigit():
print("Digit")
elif char.islower():
print("Lowercase letter")
elif char.isupper():
print("Uppercase letter")
else:
print("Special character")
```
---
### 4. Multiplication Table Generator
This generates the multiplication table of a given number.
```python
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
```
---
### 5. Fibonacci Sequence Generator (Using While Loop)
This prints Fibonacci numbers up to a given count.
```python
n = int(input("Enter the number of Fibonacci terms: "))
a, b = 0, 1
count = 0
while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1
```
---
### 6. Factorial Generator
This calculates the factorial of a number using a loop.
```python
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}")
```
---
### 7. Prime Number Analyzer (Using Function)
This checks if a number is prime or not.
```python
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter a number: "))
if is_prime(num):
print("Prime Number")
else:
print("Not a Prime Number")
```
---
### 8. Simple Calculator Using Functions
A basic calculator performing arithmetic operations.
```python
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 if y != 0 else "Cannot divide by zero"
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Choose operation (+, -, *, /): ")
if operation == '+':
print("Result:", add(num1, num2))
elif operation == '-':
print("Result:", subtract(num1, num2))
elif operation == '*':
print("Result:", multiply(num1, num2))
elif operation == '/':
print("Result:", divide(num1, num2))
else:
print("Invalid operation")
```
---
### 9. Interactive Guessing Game
A simple number guessing game with user interaction.
```python
import random
secret_number = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess the number (1-100): "))
attempts += 1
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed it in {attempts} attempts.")
break
Code- 4
Step 1: Create the Input File
1. Open Notepad or any text editor.
2. Write some text in it. Example:
3. The fox jumps over the lazy dog. A quick brown fox.
4. Save the file as input.txt in the same directory where your Python
script will be located.
Step 2: Write the Python Script
Create a Python script (extract_words.py) with the following code:
import re
def extract_words_by_length(filename, lengths):
try:
with open(filename, 'r') as file:
text = file.read()
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return
except Exception as e:
print(f"Error reading file '{filename}': {e}")
return
words = re.findall(r'\b\w+\b', text)
filtered_words = [word for word in words if len(word) in lengths]
print("Words matching the specified lengths:")
for word in filtered_words:
print(word)
if __name__ == "__main__":
file_name = 'input.txt'
desired_lengths = [3, 4, 5]
extract_words_by_length(file_name, desired_lengths)
Step 3: Run the Script
1. The output should display words of the specified lengths (3, 4, or 5
letters).
2. Finding Closest Points in 3D from a CSV File
This program reads a CSV file containing 3D coordinates and finds the
two closest points.
Step 1: Create the CSV File
1. Open Excel or a text editor.
2. Add the following lines:
3. 1.0,2.0,3.0
4. 4.0,5.0,6.0
5. 1.1,2.1,3.1
6. 7.0,8.0,9.0
7. Save it as points.csv in the same directory as your script.
Step 2: Write the Python Script
Create a file closest_points.py and add the following:
import csv
import math
def read_points_from_csv(filename):
points = []
try:
with open(filename, newline='') as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
try:
point = tuple(float(coord) for coord in row)
if len(point) != 3:
print(f"Skipping row: {row}")
continue
points.append(point)
except ValueError:
print(f"Skipping invalid row: {row}")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return points
def find_closest_points(points):
min_distance = float('inf')
closest_pair = (None, None)
for i in range(len(points)):
for j in range(i + 1, len(points)):
p1, p2 = points[i], points[j]
distance = math.sqrt(sum((a - b) ** 2 for a, b in zip(p1, p2)))
if distance < min_distance:
min_distance = distance
closest_pair = (p1, p2)
return closest_pair, min_distance
if __name__ == "__main__":
filename = 'points.csv'
points = read_points_from_csv(filename)
if len(points) < 2:
print("Not enough points to find a closest pair.")
else:
(p1, p2), distance = find_closest_points(points)
print(f"The closest points are {p1} and {p2} with a distance of
{distance:.4f}.")
Step 3: Run the Script
python closest_points.py
The output should display the two closest points and their distance.
3. Sorting City Names from a File
This script sorts city names alphabetically and writes them to a new
file.
Step 1: Create the Input File
1. Open Notepad and enter:
2. Mumbai
3. Delhi
4. Kolkata
5. Bangalore
6. Chennai
7. Save as cities.txt.
Step 2: Write the Python Script
Create sort_cities.py:
def sort_cities(input_file, output_file):
try:
with open(input_file, 'r') as file:
cities = [line.strip() for line in file if line.strip()]
except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
return
cities.sort(key=lambda city: city.lower())
try:
with open(output_file, 'w') as file:
for city in cities:
file.write(city + '\n')
except Exception as e:
print(f"Error writing to file '{output_file}': {e}")
return
print(f"Sorted cities written to '{output_file}'.")
if __name__ == "__main__":
input_filename = 'cities.txt'
output_filename = 'sorted_cities.txt'
sort_cities(input_filename, output_filename)
Step 3: Run the Script
python sort_cities.py
The sorted city names will be saved in sorted_cities.txt.
4. Creating an Executable File
Once you have created any of the Python programs above, you can turn
them into an executable file (.exe) using PyInstaller.
Step 1: Install PyInstaller
pip install pyinstaller
Step 2: Convert Python Script to Executable
To create an executable for Extracting Words script:
pyinstaller --onefile extract_words.py
• The --onefile flag bundles everything into a single .exe file.
• If you want a windowed app (without a console):
• pyinstaller --onefile --noconsole extract_words.py
Step 3: Find the Executable
• Go to the dist directory inside your project folder.
• You will find extract_words.exe (on Windows) or extract_words
(on Linux/Mac).
Step 4: Run the Executable
• On Windows:
Double-click extract_words.exe or run in the command prompt:
• dist\extract_words.exe
• On Linux/Mac:
• ./dist/extract_words
Code – 5
import logging
# 1. Basic Exception Handling
def divide_numbers():
try:
num1 = float(input("Enter the numerator: "))
num2 = float(input("Enter the denominator: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter numeric values.")
divide_numbers()
# 2. Custom Exceptions
class InsufficientFundsError(Exception):
pass
class InvalidAccountError(Exception):
pass
def withdraw_money(account_balance, amount):
if amount > account_balance:
raise InsufficientFundsError("Insufficient funds for this
transaction.")
elif account_balance <= 0:
raise InvalidAccountError("Invalid account. Balance cannot be zero
or negative.")
else:
account_balance -= amount
return account_balance
try:
balance = 500 # Example balance
amount_to_withdraw = float(input("Enter withdrawal amount: "))
new_balance = withdraw_money(balance, amount_to_withdraw)
print(f"New balance: {new_balance}")
except InsufficientFundsError as e:
print(e)
except InvalidAccountError as e:
print(e)
# 3. Logging for Debugging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s -
%(levelname)s - %(message)s')
def perform_operations():
logging.info("Starting operation...")
try:
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
logging.debug(f"Numbers entered: {x}, {y}")
result = x / y
logging.info(f"Result: {result}")
except ZeroDivisionError:
logging.error("Attempted to divide by zero.")
except ValueError:
logging.error("Invalid input provided.")
logging.info("Operation completed.")
perform_operations()
# 4. Using a Debugger
# To debug, use 'pdb':
# import pdb; pdb.set_trace()
def buggy_function():
x = 10
y = 0 # Intentional division by zero error
z = x / y # Use pdb to set breakpoints and step through code
print(z)
# Uncomment the next line and run with a debugger to analyze
# buggy_function()
# 5. Scientific Debugging Techniques
def find_bug():
numbers = [1, 2, 3, 4, 5]
total = 0
for i in range(len(numbers) + 1): # Intentional off-by-one error
total += numbers[i]
print(f"Total sum: {total}")
# Apply binary search debugging by checking midpoints
# Uncomment and run step by step
# find_bug()
Code- 6
from datetime import datetime
# Encapsulation: Defining Event class with private attributes and getter
methods
class Event:
def __init__(self, name, date, location):
self.__name = name
self.__date = datetime.strptime(date, '%Y-%m-%d')
self.__location = location
self.__participants = []
def register_participant(self, participant):
self.__participants.append(participant)
print(f"{participant.get_name()} registered for {self.__name}")
def get_details(self):
return f"Event: {self.__name}, Date: {self.__date.strftime('%Y-%m-
%d')}, Location: {self.__location}, Participants: {len(self.__participants)}"
# Inheritance: Organizer is a subclass of Event
class Organizer:
def __init__(self, name, contact):
self.name = name
self.contact = contact
def organize_event(self, event):
print(f"Organizer {self.name} is organizing {event.get_details()}")
# Inheritance: Participant class with base class Person
class Person:
def __init__(self, name, email):
self._name = name
self._email = email
def get_name(self):
return self._name
class Participant(Person):
def __init__(self, name, email, participant_type):
super().__init__(name, email)
self.participant_type = participant_type # Attendee, Speaker,
Volunteer
def get_info(self):
return f"Participant: {self._name}, Email: {self._email}, Type:
{self.participant_type}"
# Polymorphism: Different event types with overridden get_details
method
class Workshop(Event):
def __init__(self, name, date, location, topic):
super().__init__(name, date, location)
self.topic = topic
def get_details(self):
return super().get_details() + f", Topic: {self.topic}"
class Concert(Event):
def __init__(self, name, date, location, artist):
super().__init__(name, date, location)
self.artist = artist
def get_details(self):
return super().get_details() + f", Artist: {self.artist}"
# Testing the Event Management System
if __name__ == "__main__":
event1 = Workshop("AI Workshop", "2025-06-15", "Hall A", "Machine
Learning Basics")
event2 = Concert("Rock Night", "2025-07-20", "Main Auditorium", "The
Rockers")
organizer = Organizer("Alice Johnson", "[email protected]")
participant1 = Participant("Bob Smith", "
[email protected]", "Attendee")
participant2 = Participant("Charlie Brown", "[email protected]",
"Speaker")
event1.register_participant(participant1)
event1.register_participant(participant2)
event2.register_participant(participant1)
organizer.organize_event(event1)
organizer.organize_event(event2)
print(event1.get_details())
print(event2.get_details())
Code- 7
1. GUI for Developing Conversion Utilities: Develop a Python GUI
application that
performs various unit conversions such as currency (Rupees to
Dollars), temperature
(Celsius to Fahrenheit), and length (Inches to Feet). The application
should include input
fields for the values, dropdown menus or buttons to select the type of
conversion, and
labels to display the results
import tkinter as tk
from tkinter import ttk
def convert():
value = float(entry.get())
conversion_type = conversion_var.get()
result = ''
if conversion_type == 'Rupees to Dollars':
result = f'${value / 82:.2f}'
elif conversion_type == 'Celsius to Fahrenheit':
result = f'{(value * 9/5) + 32:.2f} °F'
elif conversion_type == 'Inches to Feet':
result = f'{value / 12:.2f} ft'
result_label.config(text=f'Result: {result}')
root = tk.Tk()
root.title('Unit Conversion Utilities')
root.geometry('400x200')
# Input field for value
tk.Label(root, text='Enter Value:').pack()
entry = tk.Entry(root)
entry.pack()
# Conversion type dropdown
tk.Label(root, text='Select Conversion Type:').pack()
conversion_var = tk.StringVar(value='Rupees to Dollars')
conversion_dropdown = ttk.Combobox(root,
textvariable=conversion_var)
conversion_dropdown['values'] = ('Rupees to Dollars', 'Celsius to
Fahrenheit', 'Inches to Feet')
conversion_dropdown.pack()
# Convert Button
convert_button = tk.Button(root, text='Convert', command=convert)
convert_button.pack()
# Result Label
result_label = tk.Label(root, text='Result:')
result_label.pack()
root.mainloop()
-------------------------------------------------------------------
------
2. GUI for Calculating Areas of Geometric Figures: Develop a Python GUI
application
that calculates the areas of different geometric figures such as circles,
rectangles, and
triangles. Allows users to input the necessary dimensions for various
geometric figures
and calculate their respective areas. The application should include
input fields for the
dimensions, buttons to perform the calculations, and labels to display
the results.
import tkinter as tk
from tkinter import ttk
import math
def calculate_area():
shape = shape_var.get()
try:
if shape == 'Circle':
radius = float(entry1.get())
area = math.pi * radius ** 2
result = f'Area of Circle: {area:.2f}'
elif shape == 'Rectangle':
length = float(entry1.get())
width = float(entry2.get())
area = length * width
result = f'Area of Rectangle: {area:.2f}'
elif shape == 'Triangle':
base = float(entry1.get())
height = float(entry2.get())
area = 0.5 * base * height
result = f'Area of Triangle: {area:.2f}'
result_label.config(text=result)
except ValueError:
result_label.config(text='Please enter valid numbers')
root = tk.Tk()
root.title('Geometric Area Calculator')
root.geometry('400x300')
# Shape selection
tk.Label(root, text='Select Shape:').pack()
shape_var = tk.StringVar(value='Circle')
shape_dropdown = ttk.Combobox(root, textvariable=shape_var)
shape_dropdown['values'] = ('Circle', 'Rectangle', 'Triangle')
shape_dropdown.pack()
# Dimension inputs
entry1 = tk.Entry(root)
entry1.pack()
entry2 = tk.Entry(root)
entry2.pack()
# Calculate button
calculate_button = tk.Button(root, text='Calculate Area',
command=calculate_area)
calculate_button.pack()
# Result label
result_label = tk.Label(root, text='Area:')
result_label.pack()
root.mainloop()
-------------------------------------------------------------------
----------
3. College Admission Registration Form: The college admission
registration form collects
essential personal, educational, and contact information from
prospective
students. Create a GUI as shown in Figure-1 that allows the user to
input his/her
name, branch and
favorite game. When the user clicks the Submit button, it should
display the output as
illustrated.
import tkinter as tk
from tkinter import messagebox
def submit_details():
name = name_entry.get()
branch = branch_var.get()
games = []
if cricket_var.get():
games.append('Cricket')
if football_var.get():
games.append('Football')
if badminton_var.get():
games.append('Badminton')
game_text = ' and enjoy playing ' + ', '.join(games) if games else ''
output = f'Your name is {name}.\n{name} is from {branch}
Department.{game_text}'
messagebox.showinfo('Output', output)
root = tk.Tk()
root.title('College Admission Registration Form')
root.geometry('400x300')
# Student Name
tk.Label(root, text='Enter Student Name:').pack()
name_entry = tk.Entry(root)
name_entry.pack()
# Branch Selection
tk.Label(root, text='Select Your Branch:').pack()
branch_var = tk.StringVar(value='Computer Engineering')
tk.Radiobutton(root, text='Computer Engineering', variable=branch_var,
value='Computer Engineering').pack()
tk.Radiobutton(root, text='Information Technology', variable=branch_var,
value='Information Technology').pack()
# Favorite Games
tk.Label(root, text='Select Favorite Games:').pack()
cricket_var = tk.BooleanVar()
football_var = tk.BooleanVar()
badminton_var = tk.BooleanVar()
tk.Checkbutton(root, text='Cricket', variable=cricket_var).pack()
tk.Checkbutton(root, text='Football', variable=football_var).pack()
tk.Checkbutton(root, text='Badminton', variable=badminton_var).pack()
# Submit Button
submit_button = tk.Button(root, text='Submit', command=submit_details)
submit_button.pack()
root.mainloop()
Code- 8
import re
# 1. Validate Phone Number and Email ID
def validate_phone_email():
phone_pattern = re.compile(r"^\+?[0-9]{10,15}$") # Supports
international and local numbers
email_pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-
zA-Z0-9-.]+$")
phone = input("Enter phone number: ")
email = input("Enter email ID: ")
if phone_pattern.match(phone):
print("Valid phone number.")
else:
print("Invalid phone number.")
if email_pattern.match(email):
print("Valid email ID.")
else:
print("Invalid email ID.")
# 2. Password Strength Checker
def check_password_strength():
password_pattern = re.compile(r"^(?=.*[a-z])(?=.*[A-
Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$")
password = input("Enter a password: ")
if password_pattern.match(password):
print("Strong password.")
else:
print("Weak password. Ensure it's 8+ chars, contains uppercase,
lowercase, digit, and special char.")
# 3. URL Validator
def validate_url():
url_pattern = re.compile(r"^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/\S*)?$")
url = input("Enter a URL: ")
if url_pattern.match(url):
print("Valid URL.")
else:
print("Invalid URL.")
# 4. Extract Data from Text File
def extract_data_from_file(file_path):
with open(file_path, 'r') as file:
content = file.read()
emails = re.findall(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-
.]+", content)
phone_numbers = re.findall(r"\+?[0-9]{10,15}", content)
dates = re.findall(r"\b\d{2}/\d{2}/\d{4}\b", content) # Matches
MM/DD/YYYY format
print("Extracted Emails:", emails)
print("Extracted Phone Numbers:", phone_numbers)
print("Extracted Dates:", dates)
# Testing the functions
if __name__ == "__main__":
validate_phone_email()
check_password_strength()
validate_url()
# Provide the path of a text file containing data to extract
# extract_data_from_file("data.txt")
Code- 9
import numpy as np
# 1. Creating and Manipulating Arrays
def create_arrays():
# 1D Array
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", array_1d)
# 2D Array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", array_2d)
# 3D Array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("3D Array:\n", array_3d)
# Reshaping
reshaped_array = array_1d.reshape((5, 1))
print("Reshaped 1D to 2D:\n", reshaped_array)
# Slicing and Indexing
print("Slice first row of 2D Array:", array_2d[0, :])
print("Element at (1,2) in 2D Array:", array_2d[1, 2])
# 2. Array Mathematics
def array_math():
array_a = np.array([[1, 2, 3], [4, 5, 6]])
array_b = np.array([[7, 8, 9], [10, 11, 12]])
print("Element-wise Addition:\n", array_a + array_b)
print("Element-wise Subtraction:\n", array_a - array_b)
print("Element-wise Multiplication:\n", array_a * array_b)
print("Element-wise Division:\n", array_a / array_b)
# Dot Product
vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])
dot_product = np.dot(vector1, vector2)
print("Dot Product:", dot_product)
# Cross Product
cross_product = np.cross(vector1, vector2)
print("Cross Product:", cross_product)
# 3. Statistical Operations
def statistical_operations():
data = np.array([10, 20, 30, 40, 50])
print("Mean:", np.mean(data))
print("Median:", np.median(data))
print("Standard Deviation:", np.std(data))
print("Variance:", np.var(data))
# Correlation Coefficients
data2 = np.array([5, 10, 15, 20, 25])
correlation = np.corrcoef(data, data2)
print("Correlation Coefficients:\n", correlation)
if __name__ == "__main__":
create_arrays()
array_math()
statistical_operations()
Code- 10
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Task 1: Loading and Inspecting Data
def load_and_inspect(file_path):
df = pd.read_csv(file_path)
print("First few rows:")
print(df.head())
print("\nData Types:")
print(df.dtypes)
print("\nBasic Statistics:")
print(df.describe())
return df
# Task 2: Data Cleaning
def clean_data(df):
df.fillna(df.mean(), inplace=True) # Fill missing values with column
mean
df.drop_duplicates(inplace=True) # Remove duplicates
print("\nMissing values after cleaning:")
print(df.isnull().sum())
return df
# Task 3: Data Aggregation
def aggregate_data(df):
aggregated = df.groupby("species").agg({'sepal_length': ['mean', 'min',
'max']})
print("\nAggregated Data:")
print(aggregated)
# Task 4: Plotting Graphs
def plot_graphs(df):
# Line Plot Example (COVID-19 Cases Trend)
if 'date' in df.columns and 'cases' in df.columns:
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df['cases'].plot(title='COVID-19 Cases Trend', xlabel='Date',
ylabel='Cases')
plt.show()
# Scatter Plot (Car Age vs Price)
if 'Age' in df.columns and 'Price' in df.columns:
plt.figure(figsize=(8, 5))
sns.scatterplot(x=df['Age'], y=df['Price'])
plt.title('Car Age vs Price')
plt.xlabel('Age of Car')
plt.ylabel('Price')
plt.show()
# Histogram (Kilometers Driven)
if 'Kilometers_Driven' in df.columns:
plt.figure(figsize=(8, 5))
sns.histplot(df['Kilometers_Driven'], bins=30, kde=True)
plt.title('Distribution of Kilometers Driven')
plt.show()
# Bar Plot (Car Distribution by Fuel Type)
if 'Fuel_Type' in df.columns:
plt.figure(figsize=(8, 5))
sns.countplot(x=df['Fuel_Type'])
plt.title('Distribution of Cars by Fuel Type')
plt.show()
# Pie Chart (Percentage Distribution of Fuel Types)
if 'Fuel_Type' in df.columns:
fuel_counts = df['Fuel_Type'].value_counts()
plt.figure(figsize=(8, 5))
plt.pie(fuel_counts, labels=fuel_counts.index, autopct='%1.1f%%')
plt.title('Percentage Distribution of Cars by Fuel Type')
plt.show()
# Box Plot (Car Prices across Fuel Types)
if 'Fuel_Type' in df.columns and 'Price' in df.columns:
plt.figure(figsize=(8, 5))
sns.boxplot(x='Fuel_Type', y='Price', data=df)
plt.title('Car Price Distribution by Fuel Type')
plt.show()
if __name__ == "__main__":
file_path = "your_dataset.csv" # Replace with actual dataset
df = load_and_inspect(file_path)
df = clean_data(df)
aggregate_data(df)
plot_graphs(df)