Python Programming: OOP, RegEx, and Web Scraping

Practical 1: Car Class Implementation

Purpose: Demonstrate basic Object-Oriented Programming (OOP) by creating a Car class with accelerate and brake methods.

class Car:
    def __init__(self, year, mpg, speed):
        self.year = year
        self.mpg = mpg
        self.speed = speed

    def accelerate(self):
        self.speed += 10
        print(f"The car speeds up. Current speed is {self.speed}")

    def brake(self):
        if self.speed >= 10:
            self.speed -= 10
        else:
            self.speed = 0
        print(f"The car slows down. Current speed is {self.speed}")

car1 = Car(2024, 24, 50)
car1.accelerate()
car1.brake()

Practical 2: Triangle Shape Classification

Purpose: Validate triangle angles and identify the triangle type using OOP logic.

class Triangle:
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    def check_angles(self):
        return self.angle1 + self.angle2 + self.angle3 == 180

    def triangletype(self):
        if not self.check_angles():
            print("The triangle is not valid.")
            return
        if self.angle1 == self.angle2 == self.angle3 == 60:
            print("The triangle is an Equilateral Triangle.")
        elif 90 in (self.angle1, self.angle2, self.angle3):
            print("The triangle is a Right-Angled Triangle.")
        elif self.angle1 == self.angle2 or self.angle1 == self.angle3 or self.angle2 == self.angle3:
            print("The triangle is an Isosceles Triangle.")
        else:
            print("The triangle is a Scalene Triangle.")

t1 = Triangle(60, 60, 60)
print(t1.check_angles())
t1.triangletype()
t2 = Triangle(90, 45, 45)
print(t2.check_angles())
t2.triangletype()

Practical 3: Student Information System

Purpose: Demonstrate inheritance (Person → Student) in Python OOP.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        return f"Name: {self.name} Age: {self.age}"

class Student(Person):
    def __init__(self, name, age, section):
        super().__init__(name, age)
        self.section = section

    def displayStudent(self):
        print(f"{super().display()} Section: {self.section}")

student1 = Student("Caelum", 22, "A")
student1.displayStudent()

Practical 4: Banking System

Purpose: Use OOP concepts to implement Customer, Account, and Transaction classes.

class Customer:
    def __init__(self, name, address, contact_info):
        self.name = name
        self.address = address
        self.contact_info = contact_info

    def info(self):
        return f"Name: {self.name} Address: {self.address} Contact Info: {self.contact_info}"

class Account:
    def __init__(self, account_number, account_type, balance=0):
        self.account_number = account_number
        self.account_type = account_type
        self.balance = balance

    def info(self):
        return f"Account Number: {self.account_number} Account Type: {self.account_type}"

    def deposit(self, amount):
        self.balance += amount
        print(f"Amount {amount} Successfully Deposited. Current balance: {self.balance}")

    def withdraw(self, amount):
        if amount > self.balance:
            print(f"Insufficient Balance. Current balance: {self.balance}")
        else:
            self.balance -= amount
            print(f"Amount {amount} Successfully Withdrawn. Current balance: {self.balance}")

    def get_balance(self):
        return f"Current Balance: {self.balance}"

class Transactions:
    def __init__(self, transaction_type, amount):
        self.transaction_type = transaction_type
        self.amount = amount

    def display_transaction(self):
        return f"Transaction Type: {self.transaction_type} Amount to be Transacted: {self.amount}"

customer1 = Customer("Caelum", "London, UK", "caelum@gmail.com")
print(customer1.info())
account1 = Account("1234567890", "Savings", 10000)
print(account1.info())
print(account1.get_balance())
t1 = Transactions("Deposit", 5000)
account1.deposit(t1.amount)
print(t1.display_transaction())
t2 = Transactions("Withdraw", 3000)
account1.withdraw(t2.amount)
print(t2.display_transaction())

Practical 5: Email and Password Validation

Purpose: Validate email and extract data from websites and files using Regular Expressions.

import re
import requests
import os

# 1. Verify validity of an Email address
pattern1 = r'^[A-Za-z0-9._%+]{1,20}@[A-Za-z0-9+]{2,20}\.[A-Za-z]{2,3}$'
def validate_email(email):
    return bool(re.match(pattern1, email))

email = input("Enter the email address: ")
if validate_email(email):
    print("Entered Email is valid.")
else:
    print("Entered Email is invalid.")

# 2. Extract all email IDs from a webpage
url = 'https://sspu.ac.in/'
response = requests.get(url)
if response.status_code == 200:
    html = response.text
    pattern2 = r'[A-Za-z0-9._%+]{1,20}@[A-Za-z0-9+]{2,20}\.[A-Za-z]{2,3}'
    emails = re.findall(pattern2, html)
    print("Emails found: ", emails)

# 3. Extract all email IDs from a local file
file_path = r"C:\Users\vedang\OneDrive\Documents\sample.txt"
if os.path.exists(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        text = f.read()
    pattern3 = r'[A-Za-z0-9._%+]{1,20}@[A-Za-z0-9+]{2,20}\.[A-Za-z]{2,3}'
    emails = re.findall(pattern3, text)
    print("Emails Found in File: ", emails)

# 4. Verify password validity
def is_valid_password(password):
    pattern4 = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%])[A-Za-z\d@#$%]{8,20}$'
    return bool(re.fullmatch(pattern4, password))

password = input("Enter your password: ")
if is_valid_password(password):
    print(f"{password} is a valid password.")
else:
    print(f"{password} is not a valid password.")

Practical 6: Phone Number Verification

Purpose: Validate and extract phone numbers from web and file sources using RegEx.

import re
import requests

# 1. Verify a phone number
patterns = [
    r'^\d{3,4}-\d{6,8}$', 
    r'^[6-9]\d{9}$', 
    r'^\+\d{1,3}-[6-9]\d{9}$', 
    r'^\+\d{1,3}[6-9]\d{9}$'
]

def verify_phone_number(number):
    for pattern in patterns:
        if re.match(pattern, number):
            return f"Valid phone number: {number}"
    return f"Invalid phone number: {number}"

phone_number = input("Enter a phone number to verify: ")
print(verify_phone_number(phone_number))

# 2. Extract phone numbers from a webpage
pattern_extract = r'(\b\d{3,4}-\d{6,8}\b|\b\d{10}\b|\+\d{2}-?\d{10}\b)'
url = "https://sspu.ac.in/"
response = requests.get(url)
numbers = re.findall(pattern_extract, response.text)
print("Phone Numbers Found on Website:", numbers)

# 3. Extract phone numbers from a file
file_path = "C:\\Users\\vedang\\OneDrive\\Documents\\sample2.txt"
with open(file_path, "r", encoding="utf-8") as f:
    text = f.read()
numbers_file = re.findall(pattern_extract, text)
print("Phone Numbers Found in File:", numbers_file)

Practical 7: Web Scraping Weather Forecast

Purpose: Extract weather forecast data using BeautifulSoup.

import bs4
from bs4 import BeautifulSoup as bs
import requests

page = requests.get("https://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4194")
soup = bs(page.content, 'html.parser')
seven_day = soup.find(id="seven-day-forecast")
forecast_items = seven_day.find_all(class_="tombstone-container")
tonight = forecast_items[0]
print(tonight.prettify())

Skill 1: Integer to Roman Conversion

Purpose: Convert an integer into Roman numeral format.

class IntegerToRoman:
    def convert(self, num):
        roman = ""
        symbols = {1000: "M", 900: "CM", 500: "D", 400: "CD",
                   100: "C", 90: "XC", 50: "L", 40: "XL",
                   10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"}
        for value in sorted(symbols.keys(), reverse=True):
            count = num // value
            roman += symbols[value] * count
            num %= value
        return roman

obj = IntegerToRoman()
print(obj.convert(1994))

Skill 2: Roman to Integer Conversion

Purpose: Convert Roman numeral strings into integer values.

class RomanToInteger:
    def convert(self, roman):
        roman_numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50,
                          'C': 100, 'D': 500, 'M': 1000}
        total = 0
        prev_value = 0
        for char in reversed(roman):
            value = roman_numerals[char]
            if value < prev_value:
                total -= value
            else:
                total += value
            prev_value = value
        return total

obj = RomanToInteger()
print(obj.convert("MCMXCIV"))

Skill 3: PAN and IFSC Validation

Purpose: Validate PAN numbers and IFSC codes using Regular Expressions.

import re

# 1. Validate PAN card number
pan_pattern = r'^[A-Z]{5}[0-9]{4}[A-Z]{1}$'
def validate_PAN(PAN):
    return bool(re.match(pan_pattern, PAN))

# 2. Validate IFSC code
ifsc_pattern = r'^[A-Z]{4}0[A-Z0-9]{6}$'
def is_valid_IFSC(code):
    return bool(re.fullmatch(ifsc_pattern, code))

print("Testing PAN: ABCDE1234F ->", validate_PAN("ABCDE1234F"))
print("Testing IFSC: HDFC0001234 ->", is_valid_IFSC("HDFC0001234"))

Skill 4: Aadhaar and Alphanumeric Validation

Purpose: Validate Aadhaar numbers and check if text is alphanumeric.

import re

# 1. Validate Aadhaar card number
aadhaar_pattern = r'^[2-9][0-9]{11}$'
def validate_Aadhaar(aadhaar):
    return bool(re.fullmatch(aadhaar_pattern, aadhaar))

# 2. Check if text is alphanumeric
alnum_pattern = r'^[A-Za-z0-9]+$'
def is_alphanumeric(text):
    return bool(re.fullmatch(alnum_pattern, text))

print("Aadhaar Valid:", validate_Aadhaar("234567890123"))
print("Is Alphanumeric:", is_alphanumeric("Hello123"))

Skill 5: Credit Card Validation

Purpose: Validate Mastercard and American Express cards using RegEx.

import re

def is_valid_credit_card(card_number):
    AMExp_pattern = r"^3[47][0-9]{13}$"
    mastercard_pattern = r"^5[1-5][0-9]{14}$"
    if re.match(AMExp_pattern, card_number):
        return "Valid American Express Card."
    elif re.match(mastercard_pattern, card_number):
        return "Valid Mastercard."
    else:
        return "Invalid card."

print(is_valid_credit_card("341234567890123"))

Skill 7: Database Operations Using Python

Purpose: Demonstrate MySQL database operations including Create, Insert, Select, Update, and Delete.

import mysql.connector

# 1. Creating a database
dataBase = mysql.connector.connect(host="localhost", user="root", passwd="12875")
cursorObject = dataBase.cursor()
cursorObject.execute("CREATE DATABASE IF NOT EXISTS gfg")

# 2. Creating a table
dataBase = mysql.connector.connect(host="localhost", user="root", passwd="12875", database="gfg")
cursorObject = dataBase.cursor()
studentRecord = """CREATE TABLE IF NOT EXISTS STUDENT (
    NAME VARCHAR(20) NOT NULL, 
    BRANCH VARCHAR(50), 
    ROLL INT NOT NULL, 
    SECTION VARCHAR(5), 
    AGE INT )"""
cursorObject.execute(studentRecord)

# 3. Inserting data
sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE) VALUES (%s, %s, %s, %s, %s)"
val = ("Arjun", "MTRX", "57", "B", "19")
cursorObject.execute(sql, val)
dataBase.commit()

# 4. Selecting with filter
query = "SELECT * FROM STUDENT WHERE AGE >= 20 AND BRANCH = 'MTRX'"
cursorObject.execute(query)
for x in cursorObject.fetchall():
    print(x)

# 5. Updating and Deleting
cursorObject.execute("UPDATE STUDENT SET AGE = 23 WHERE NAME = 'Arjun'")
cursorObject.execute("DELETE FROM STUDENT WHERE NAME = 'Kiran'")
dataBase.commit()
dataBase.close()

Skill 6: Web Scraping BBC News Headlines

Purpose: Extract top news headlines from the BBC website and display them in a DataFrame.

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "https://www.bbc.com/news"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

headlines = soup.find_all("h2")
b = [h.get_text(strip=True) for h in headlines[:10]]

df = pd.DataFrame(b, columns=["Headlines"])
print(df)