Python Applications
Python Applications
avg = sum(BUFFER)/len(BUFFER)
print("MEAN ROOM TEMPERATURE:", avg, "°C")
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]
# 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"))
@app.route("/ping")
def ping(): return jsonify(status="OK")
if __name__ == "__main__":
app.run()
with open("server.log") as f:
errors = [line for line in f if "ERROR" in line]
print("ERROR COUNT:", len(errors))
try:
charge("4111-xxxx-xxxx-1234", 250)
except ConnectionError as e:
print("RETRY LATER ‑", e)
except Exception as e:
print("PAYMENT FAILED:", e)
def read_lidar():
raise RuntimeError("SENSOR BLOCKED")
try:
distance = read_lidar()
except RuntimeError as e:
print("ENGAGE SAFE-STOP 🚨:", e)
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"
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
for _ in range(10):
fetch()
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()
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]
@app.post("/transfer")
def transfer():
data = request.json
# FAKE FUNDS MOVE
return jsonify(status="SUCCESS", ref="TXN123")
app.run()
@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)
URLS = ["https://example.com"]*10
def fetch(url):
soup = bs4.BeautifulSoup(requests.get(url).text, "html.parser")
return soup.title.string
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