Python Mini Projects
Mini projects क्यों बनाएँ?
Lessons पढ़ने से syntax आता है; projects से programming आती है। नीचे का हर project इस course के कई topics – functions, loops, dictionaries, files, JSON/CSV और error handling – को एक छोटे tool में जोड़ता है जिसे आप portfolio या practical file में दिखा सकते हैं।
| Project | कौन सी skills | Level |
|---|---|---|
| 1. Expense tracker | loops, functions, dict, JSON file, menus | Beginner+ |
| 2. Password generator | secrets, string, any(), sets | Beginner |
| 3. Quiz game | JSON, random, enumerate, zip, input | Beginner |
| 4. Attendance report | csv, Counter, f-string formatting | Beginner+ |
Project 1: data याद रखने वाला Expense tracker
Menu वाला program जो खर्च जोड़ता है, उन्हें expenses.json में रखता है और text bar chart के साथ category-wise report छापता है। Program बंद करने के बाद भी data बचा रहता है।
"""Expense tracker – saves to expenses.json between runs."""
import json
from datetime import date
from pathlib import Path
FILE = Path("expenses.json")
CATEGORIES = ["food", "travel", "books", "bills", "other"]
def load():
if FILE.exists():
return json.loads(FILE.read_text(encoding="utf-8"))
return []
def save(expenses):
FILE.write_text(json.dumps(expenses, indent=2), encoding="utf-8")
def add(expenses):
amount = float(input("Amount (₹): "))
category = input(f"Category {CATEGORIES}: ").strip().lower()
if category not in CATEGORIES:
category = "other"
note = input("Note: ").strip()
expenses.append({"date": date(2026, 10, 25).isoformat(), "amount": amount, "category": category, "note": note})
save(expenses)
print("✅ saved")
def report(expenses):
total = sum(e["amount"] for e in expenses)
print(f"Total spent: ₹{total:,.0f}")
by_cat = {}
for e in expenses:
by_cat[e["category"]] = by_cat.get(e["category"], 0) + e["amount"]
for cat, amt in sorted(by_cat.items(), key=lambda x: -x[1]):
bar = "█" * int(amt / total * 20)
print(f" {cat:<7} ₹{amt:>7,.0f} {bar}")
def main():
expenses = load()
while True:
choice = input("\n1) Add 2) Report 3) Quit → ")
if choice == "1":
add(expenses)
elif choice == "2":
report(expenses)
elif choice == "3":
print("Bye!")
break
else:
print("Please type 1, 2 or 3")
if __name__ == "__main__":
main()Path.read_text/write_textसे file code छोटा रहता है।- ग़लत category पर crash की जगह “other”।
- Report categories को रक़म से sort करके
"█" * nसे bars बनाती है। - सुधारें: खर्च delete करना, महीने का filter, CSV export।
Output एक जैसा रहे इसलिए demo में तय date है। अपनी copy में date(2026, 10, 25) को date.today() से बदलें।
Project 2: मज़बूत password generator और checker
"""Strong password generator + strength checker."""
import secrets
import string
def generate(length=12):
if length < 8:
raise ValueError("use at least 8 characters")
pools = [string.ascii_lowercase, string.ascii_uppercase, string.digits, "!@#$%&*?"]
chars = [secrets.choice(pool) for pool in pools] # one from each pool
everything = "".join(pools)
chars += [secrets.choice(everything) for _ in range(length - len(chars))]
secrets.SystemRandom().shuffle(chars)
return "".join(chars)
def strength(pw):
checks = {
"8+ characters": len(pw) >= 8,
"lowercase": any(c.islower() for c in pw),
"uppercase": any(c.isupper() for c in pw),
"digit": any(c.isdigit() for c in pw),
"symbol": any(not c.isalnum() for c in pw),
"not common": pw.lower() not in {"password", "12345678", "qwerty123", "india@123"},
}
score = sum(checks.values())
missing = [name for name, ok in checks.items() if not ok]
label = "strong" if score == 6 else "medium" if score >= 4 else "weak"
return label, missing
new = generate(14)
print("generated length:", len(new), "| strength:", strength(new)[0])
for pw in ["india@123", "Gagan2026", "Riya#Delhi2026"]:
label, missing = strength(pw)
print(f"{pw:<15} {label:<7} missing: {', '.join(missing) or '-'}")- Passwords के लिए
randomनहीं,secrets– यह security के लिए बना है। - हर pool से एक character लेने से हर नियम पूरा होना पक्का है।
- Checker बताता है कि password कमज़ोर क्यों है, जो सिर्फ़ score से ज़्यादा उपयोगी है।
Project 3: JSON file से Quiz game
[
{"q": "Which keyword defines a function in Python?", "options": ["func", "def", "function", "define"], "answer": 1},
{"q": "What does len([3, 5, 7]) return?", "options": ["2", "3", "7", "15"], "answer": 1},
{"q": "Which type is immutable?", "options": ["list", "dict", "set", "tuple"], "answer": 3}
]"""Quiz game – questions come from a JSON file, score is saved."""
import json
import random
random.seed(7) # remove this line for a different order every time
with open("questions.json", encoding="utf-8") as f:
questions = json.load(f)
random.shuffle(questions)
score = 0
for i, q in enumerate(questions, start=1):
print(f"\nQ{i}. {q['q']}")
for letter, option in zip("abcd", q["options"]):
print(f" {letter}) {option}")
answer = input("Your answer: ").strip().lower()
correct = "abcd"[q["answer"]]
if answer == correct:
score += 1
print("✔ Correct")
else:
print(f"✘ Wrong – correct answer is {correct}) {q['options'][q['answer']]}")
print(f"\nScore: {score}/{len(questions)} ({score / len(questions):.0%})")सवाल JSON file में हैं, इसलिए teacher code छुए बिना 50 नए सवाल जोड़ सकता है। Ideas: हर सवाल का timer, categories, high scores file में save।
Project 4: CSV register से Attendance report
name,Mon,Tue,Wed,Thu,Fri,Sat Asha,P,P,P,P,P,P Ravi,P,A,P,A,A,P Neha,P,P,A,P,P,P Kabir,A,P,P,P,A,A
"""Attendance summary from a CSV register."""
import csv
from collections import Counter
with open("attendance.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
days = [d for d in rows[0] if d != "name"]
print(f"{'Name':<8} {'Present':>7} {'%':>6} Status")
present_per_day = Counter()
for r in rows:
present = sum(r[d] == "P" for d in days)
for d in days:
present_per_day[d] += r[d] == "P"
pct = present / len(days) * 100
status = "OK" if pct >= 75 else "⚠ below 75%"
print(f"{r['name']:<8} {present:>7} {pct:>5.0f}% {status}")
low_day, count = min(present_per_day.items(), key=lambda x: x[1])
print(f"\nLowest attendance: {low_day} ({count}/{len(rows)} students)")Teachers register को Google Sheets से CSV में export करके एक सेकंड में यह report पा सकते हैं। आगे बढ़ाएँ: 75% से कम वाले students के parents को email, या matplotlib से attendance chart।
और project ideas (पहले कौन सा lesson पढ़ें)
| Project | पहले पढ़ें |
|---|---|
| Free API से Weather report | APIs और requests |
| Price list scraper से CSV | Web scraping |
| SQLite के साथ Library management | SQLite के साथ SQL |
| Student marks dashboard | Student performance project |
| Tests के साथ Bill generator | Testing और debugging |
Project कैसे present करें
- हर project को अपने folder में
README.mdके साथ रखें: क्या करता है, कैसे चलाएँ, sample output। - Packages हों तो
requirements.txtजोड़ें। - GitHub पर upload करके link resume में जोड़ें।
- एक design फ़ैसला समझाने को तैयार रहें (जैसे JSON क्यों, secrets क्यों)।
