0% found this document useful (0 votes)
2 views8 pages

Python Applications

The document provides a comprehensive overview of various Python programming concepts and their applications, including basics like variables and data types, control flow, data structures, functions, modules, file handling, exception handling, and object-oriented programming. It also covers advanced topics such as iterators, generators, decorators, data analysis, database interactions, logging, web frameworks like Flask, and memory management. Each section includes code snippets demonstrating practical implementations in areas like e-commerce, IoT, trading systems, and machine learning.

Uploaded by

m83609544
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Python Applications

The document provides a comprehensive overview of various Python programming concepts and their applications, including basics like variables and data types, control flow, data structures, functions, modules, file handling, exception handling, and object-oriented programming. It also covers advanced topics such as iterators, generators, decorators, data analysis, database interactions, logging, web frameworks like Flask, and memory management. Each section includes code snippets demonstrating practical implementations in areas like e-commerce, IoT, trading systems, and machine learning.

Uploaded by

m83609544
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

ONE – PYTHON BASICS: VARIABLES & DATATYPES & OPERATORS

E-COMMERCE PRICE CALCULATIONS [1]

price = 999.0 # LIST PRICE


discount= 0.15 # 15 % OFF
tax = 0.08 # 8 % SALES TAX

subtotal = price * (1-discount)


total = subtotal * (1+tax)

print(f"FINAL CHECK-OUT TOTAL: ₹{total:,.2f}")

IOT SENSOR DATA PROCESSING [1]

import random, time

def read_sensor(): # FAKE TEMPERATURE SENSOR


return round(random.uniform(20, 30), 2) # °C

BUFFER = [] # IN-MEMORY CACHE


while len(BUFFER) < 5: # COLLECT 5 READINGS
BUFFER.append(read_sensor())
time.sleep(1)

avg = sum(BUFFER)/len(BUFFER)
print("MEAN ROOM TEMPERATURE:", avg, "°C")

TWO – CONTROL FLOW: CONDITIONAL STATEMENTS & LOOPS


AUTOMATED TRADING SYSTEMS [1]

price_feed = [105, 99, 101, 96, 92] # LIVE TICKS


TARGET_BUY = 100
TARGET_SELL = 104

for tick in price_feed: # LOOP OVER STREAM


if tick <= TARGET_BUY:
print("BUY @", tick)
elif tick >= TARGET_SELL:
print("SELL @", tick)

CHATBOT CONVERSATION FLOW [1]

intents = {"HI": "HELLO! 👋", "BYE": "GOOD-BYE!", "HELP": "SURE, HOW CAN I HELP?"}
while True:
msg = input("YOU: ").upper()
if msg in intents:
print("BOT:", intents[msg])
else:
print("BOT: SORRY, I DIDN’T UNDERSTAND.")
if msg == "BYE":
break

THREE – DATA STRUCTURES: LISTS & TUPLES & SETS & DICTIONARIES
SOCIAL MEDIA FEED ALGORITHMS [1]

posts = [
{"id": 1, "likes": 120, "ts": 1718600000},
{"id": 2, "likes": 250, "ts": 1718700000},
{"id": 3, "likes": 180, "ts": 1718650000},
]
feed = sorted(posts, key=lambda p: (p["likes"], p["ts"]), reverse=True)
print([p["id"] for p in feed]) # [2,3,1]

INVENTORY MANAGEMENT SYSTEMS [1]

inventory = {"LAPTOP": 12, "MOUSE": 85, "MONITOR": 7}


order = {"LAPTOP": 2, "MOUSE": 3}

for item, qty in order.items():


if inventory.get(item,0) >= qty:
inventory[item] -= qty

print("UPDATED STOCK:", inventory)

FOUR – FUNCTIONS: LAMBDA & MAP & FILTER


DATA CLEANING PIPELINES [1]

raw = ["Alice ", None, " Bob", "", "Eve "]


clean = list(map(lambda s: s.strip(), filter(None, raw)))
print(clean) # ['Alice', 'Bob', 'Eve']

IMAGE PROCESSING APPLICATIONS [1]

from PIL import Image, ImageFilter # pip install pillow


img = Image.open("photo.jpg")
blurred = img.filter(ImageFilter.GaussianBlur(4))
blurred.save("photo_blur.jpg")
FIVE – MODULES: IMPORT & STANDARD OVERVIEW
MICROSERVICES ARCHITECTURE [1]

# user_service.py
def get_user(uid): return {"id": uid, "name": "ALICE"}

# order_service.py
from user_service import get_user
def place_order(uid, item):
user = get_user(uid)
return {"user": user, "item": item}

print(place_order(1, "BOOK"))

API DEVELOPMENT [1]

from flask import Flask, jsonify


app = Flask(__name__)

@app.route("/ping")
def ping(): return jsonify(status="OK")

if __name__ == "__main__":
app.run()

SIX – FILE HANDLING: FILE OPERATION & FILE PATH


LOG ANALYSIS SYSTEMS [1]

with open("server.log") as f:
errors = [line for line in f if "ERROR" in line]
print("ERROR COUNT:", len(errors))

DOCUMENT MANAGEMENT SYSTEMS [1]

from pathlib import Path


uploads = Path("uploads")
pdfs = list(uploads.rglob("*.pdf"))
print("TOTAL PDF FILES:", len(pdfs))

SEVEN – EXCEPTION HANDLING


PAYMENT PROCESSING SYSTEMS [1]

def charge(card, amount):


if amount <= 0: raise ValueError("INVALID AMOUNT")
# SIMULATE GATEWAY FAILURE
raise ConnectionError("NETWORK DOWN")

try:
charge("4111-xxxx-xxxx-1234", 250)
except ConnectionError as e:
print("RETRY LATER ‑", e)
except Exception as e:
print("PAYMENT FAILED:", e)

AUTONOMOUS VEHICLE SOFTWARE [1]

def read_lidar():
raise RuntimeError("SENSOR BLOCKED")

try:
distance = read_lidar()
except RuntimeError as e:
print("ENGAGE SAFE-STOP 🚨:", e)

EIGHT – CLASS AND OBJECTS (OOP)


GAME DEVELOPMENT [1]

class Player:
def __init__(self, name, hp=100): self.name, self.hp = name, hp
def attack(self, target): target.hp -= 10
def __str__(self): return f"{self.name}:{self.hp}HP"

p1, p2 = Player("KNIGHT"), Player("ORC")


p1.attack(p2)
print(p1, p2)

ENTERPRISE RESOURCE PLANNING (ERP) [1]

class Employee: # BASE CLASS


def __init__(self, eid, name): self.eid, self.name = eid, name

class Manager(Employee): # INHERITANCE


def approve_leave(self, days): print(self.name, "APPROVED", days, "DAYS")

mgr = Manager(101, "PRIYA")


mgr.approve_leave(3)

NINE – ADVANCED PYTHON CONCEPTS: ITERATORS & GENERATORS &


DECORATORS
BIG DATA PROCESSING [1]

def stream_file(path):
with open(path) as f:
for line in f: # GENERATOR YIELDS ONE ROW AT A TIME
yield line.strip().split(",")
for row in stream_file("huge.csv"):
pass # PROCESS

API RATE LIMITING [1]

from time import time, sleep


def rate_limit(calls_per_sec):
def deco(fn):
last=[^0]
def wrapper(*a, **k):
elapsed=time()-last[^0]
if elapsed < 1/calls_per_sec:
sleep(1/calls_per_sec - elapsed)
last[^0]=time()
return fn(*a, **k)
return wrapper
return deco

@rate_limit(5) # MAX 5 CALLS/SEC


def fetch():
print("API HIT")

for _ in range(10):
fetch()

TEN – DATA ANALYSIS WITH PYTHON


FINANCIAL MARKET ANALYSIS [1]

import pandas as pd, matplotlib.pyplot as plt


df = pd.read_csv("prices.csv", parse_dates=["Date"], index_col="Date")
df["SMA20"] = df["Close"].rolling(20).mean()
df[["Close","SMA20"]].plot(title="20-DAY MOVING AVERAGE")
plt.show()

HEALTHCARE DATA ANALYTICS [1]

import seaborn as sns, pandas as pd


patients = pd.read_csv("patients.csv")
sns.boxplot(x="Diagnosis", y="Age", data=patients)

ELEVEN – WORKING WITH DATABASES: SQLITE


MOBILE APP DEVELOPMENT [1]

import sqlite3, pathlib


db = pathlib.Path("app.db")
con = sqlite3.connect(db)
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS prefs(key TEXT, val TEXT)")
cur.execute("INSERT INTO prefs VALUES(?,?)", ("THEME","DARK"))
con.commit()

SMALL BUSINESS MANAGEMENT [1]

def total_sales():
with sqlite3.connect("shop.db") as con:
cur = con.cursor()
cur.execute("SELECT SUM(amount) FROM orders")
print("TOTAL SALES:", cur.fetchone()[^0])
total_sales()

TWELVE – LOGGING IN PYTHON


PRODUCTION WEB APPLICATIONS [1]

import logging, logging.config


logging.basicConfig(level=logging.INFO, filename="app.log",
format="%(asctime)s %(levelname)s %(message)s")
logging.info("SERVICE STARTED")

CYBERSECURITY MONITORING [1]

sec_log = logging.getLogger("security")
net_log = logging.getLogger("network")
handler = logging.FileHandler("security.log")
sec_log.addHandler(handler); net_log.addHandler(handler)
sec_log.warning("UNUSUAL LOGIN LOCATION")

THIRTEEN – FLASK
FINTECH APPLICATIONS [1]

from flask import Flask, request, jsonify


app = Flask(__name__)

@app.post("/transfer")
def transfer():
data = request.json
# FAKE FUNDS MOVE
return jsonify(status="SUCCESS", ref="TXN123")

app.run()

HEALTHCARE MANAGEMENT SYSTEMS [1]

@app.get("/patient/<pid>")
def patient(pid):
record = {"id": pid, "name": "JOHN", "bp": "120/80"}
return jsonify(record)
FOURTEEN – STREAMLIT
MACHINE LEARNING MODEL DEPLOYMENT [1]

# streamlit_app.py
import streamlit as st, joblib
clf = joblib.load("model.pkl")
val = st.slider("SEPAL LENGTH", 4.0, 8.0, 5.1)
pred = clf.predict([[val,3.5,1.4,0.2]])[^0]
st.write("PREDICTED SPECIES:", pred)

BUSINESS INTELLIGENCE DASHBOARDS [1]

import pandas as pd, streamlit as st


sales = pd.read_csv("sales.csv")
st.bar_chart(sales.groupby("Region")["Revenue"].sum())

FIFTEEN – MEMORY MANAGEMENT


HIGH-FREQUENCY TRADING SYSTEMS [1]

import array # LOW-OVERHEAD NUMERIC BUFFER


ticks = array.array('d', (0.0 for _ in range(1_000_000)))

SCIENTIFIC COMPUTING [1]

import numpy as np, sys


mat = np.zeros((1000,1000), dtype=np.float32)
print("MEMORY USED (MB):", sys.getsizeof(mat)/1e6)

SIXTEEN – MULTITHREADING & MULTIPROCESSING


WEB SCRAPING OPERATIONS [1]

from concurrent.futures import ThreadPoolExecutor


import requests, bs4

URLS = ["https://example.com"]*10
def fetch(url):
soup = bs4.BeautifulSoup(requests.get(url).text, "html.parser")
return soup.title.string

with ThreadPoolExecutor(8) as ex:


titles = list(ex.map(fetch, URLS))
print(titles)

CRYPTOCURRENCY MINING SOFTWARE [1]

import hashlib, os
from multiprocessing import Pool
def sha256(nonce): # CPU-INTENSIVE HASH
return hashlib.sha256(str(nonce).encode()).hexdigest()

with Pool(os.cpu_count()) as p:
hashes = p.map(sha256, range(1_000_000))
print("COMPUTED", len(hashes), "HASHES")

1. REAL-USE-CASES.pdf

You might also like