Python Programming Cheatsheet: Important Steps, Syntax & Practical Guide

Job-Oriented 16-Module Syllabus

Python Real-World Programming Masterclass: From Fundamentals to Full Stack, Automation & AI

Forget superficial syntax and simple one-liners. For real employment and freelancing success, our curriculum connects Python + Database + Excel Automation + REST APIs + Flask + AI Basics + Real-World Projects across 3 structured career levels.

Pragati Skill Academy 3-Level Career Track Architecture

Career Track Level Modules Included Key Practical Skills Acquired Benchmark Practice Project
Level 1 — Python Beginner Modules 1 to 4 Syntax, Data Types, If-Else, Loops, Lists, Slicing, Dictionaries, Functions, *args, **kwargs, Lambda Marksheet Generator, Calculator & Student Management Data System
Level 2 — Python Professional Modules 5 to 11 File I/O (CSV/JSON), Exception Handling, OOP (Encapsulation/Inheritance), openpyxl & pandas Excel automation, MySQL/SQLite CRUD & Transactions, Email/PDF Automation Automated Student Fee & Attendance Report Generator, Error-Safe Billing Application
Level 3 — Python Career Track Modules 12 to 16 REST APIs (requests), Flask Web Development (Routes, Jinja2, Auth, MySQL), NumPy/Pandas Data Analytics & Charts, Gemini/OpenAI API integration, Git & GitHub Portfolio Full Stack Student Management Web App, Business Automation System, AI Quiz Generator

The 16-Module Complete Job-Oriented Syllabus Overview

  1. Module 1 — Python Fundamentals: Python installation, VS Code, Interpreter, variables, data types (int, float, str, bool, None), type casting, input/output, comments, all 6 operator families.
  2. Module 2 — Conditional & Loop: if/elif/else, nested conditions, for loop, while loop, break, continue, pass, range() mechanics.
  3. Module 3 — Python Data Structures: String, List, Tuple, Set, Dictionary, index slicing [start:stop:step], list/dictionary methods, nested collections, list comprehensions.
  4. Module 4 — Functions: Defining functions, parameters, return value, default & keyword args, *args, **kwargs, lambda functions, scope, recursion.
  5. Module 5 — File Handling: Open/Close with context managers, read/write/append, CSV files, JSON files, folder operations with os & pathlib.
  6. Module 6 — Error Handling: Syntax vs runtime errors, try, except, else, finally, raise, custom exceptions, error logging.
  7. Module 7 — Object-Oriented Programming (OOP): Class & Object, __init__ constructor, instance variables & methods, encapsulation, inheritance, polymorphism, abstraction, class & static methods.
  8. Module 8 — Python Modules & Packages: Modules, import, standard libraries (os, sys, datetime, math, random, json, csv), pip, venv virtual environment, requirements.txt, environment variables.
  9. Module 9 — Python + Excel Automation: Excel read/write, openpyxl, pandas, data cleaning, filtering, sorting, duplicate removal, automatic report generation, Excel formatting.
  10. Module 10 — Python + Database: Database concepts, SQL basics, MySQL / SQLite, Python database connection, CRUD operations, search, filtering, joins, transactions & commits.
  11. Module 11 — Python Workplace Automation: File/folder automation, PDF processing, email automation with attachments (smtplib), scheduled tasks, bulk file rename, automated reports.
  12. Module 12 — Web & API with Python: HTTP basics, REST API concepts, JSON data, GET/POST/PUT/DELETE, requests library, API authentication.
  13. Module 13 — Flask Web Development: Flask setup, routes, Jinja2 templates, forms, static files, database integration, CRUD web application, login system, session management.
  14. Module 14 — Python for Data Analysis: NumPy basics, Pandas Series & DataFrames, missing data handling, GroupBy, merge, pivot tables, Matplotlib charts & visualizations.
  15. Module 15 — Python + AI Basics: AI/ML concepts, using AI APIs (Google Gemini / OpenAI), prompt + API integration, text generation, structured JSON output, AI chatbot basics.
  16. Module 16 — Git & GitHub: Git concepts, repository, commit, push/pull, branching, GitHub, README.md, live project portfolio creation.

Module 1: Core Logic Building & Classic Algorithm Drills

Before touching frameworks or AI, every software engineer must master algorithmic thinking and conditional logic. Below are real, runnable solutions to classic interview and logic drills:

1. Prime Number Sieve & Efficiency

# Highly optimized Prime Number checker with O(sqrt(N)) complexity
def is_prime(n: int) -> bool:
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

# Test
numbers_to_test = [2, 17, 25, 49, 97, 100]
print({num: is_prime(num) for num in numbers_to_test})
# Output: {2: True, 17: True, 25: False, 49: False, 97: True, 100: False}

2. Fibonacci Sequence (Iterative & Dynamic Programming with Memoization)

# 1. Iterative O(N) Time, O(1) Space - Best for production
def fibonacci_iterative(n: int) -> list[int]:
    if n <= 0:
        return []
    if n == 1:
        return [0]
    series = [0, 1]
    for _ in range(2, n):
        series.append(series[-1] + series[-2])
    return series

# 2. Recursive with lru_cache memoization to prevent O(2^N) stack explosion
from functools import lru_cache

@lru_cache(maxsize=None)
def fib_memoized(n: int) -> int:
    if n < 2:
        return n
    return fib_memoized(n - 1) + fib_memoized(n - 2)

print("First 10 Fibonacci numbers:", fibonacci_iterative(10))
print("50th Fibonacci number:", fib_memoized(50))

3. Palindrome & Armstrong Number Verification

# Palindrome check (ignoring case, punctuation and spaces)
import re

def is_palindrome_sentence(s: str) -> bool:
    cleaned = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
    return cleaned == cleaned[::-1]

print(is_palindrome_sentence("A man, a plan, a canal: Panama"))  # True

# Armstrong Number (e.g. 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153)
def is_armstrong(num: int) -> bool:
    digits = [int(d) for d in str(num)]
    power = len(digits)
    return sum(d ** power for d in digits) == num

print([x for x in range(100, 1000) if is_armstrong(x)])
# Output: [153, 370, 371, 407]

Module 2: Advanced Data Structure Manipulation in Real Code

1. Deep Slicing, Matrix Transpose & Flattening

# 2D Matrix (3x3)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Transpose Matrix (Rows become Columns) using zip
transposed = [list(row) for row in zip(*matrix)]
print("Transposed Matrix:", transposed)
# Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

# Flatten 2D list into 1D using nested comprehension
flattened = [val for row in matrix for val in row]
print("Flattened:", flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slicing: Reverse every even-indexed element
original = [10, 20, 30, 40, 50, 60, 70, 80]
print("Step slicing [::2]:", original[::2])  # [10, 30, 50, 70]
print("Reversed list [::-1]:", original[::-1])

2. Dictionary Deep Dive & Collections Module (Counter, defaultdict)

from collections import Counter, defaultdict

# 1. Frequency Counter for words in a text
corpus = "python is fast python is simple python powers machine learning and python is versatile"
words = corpus.split()
word_counts = Counter(words)
print("Top 2 Most Common Words:", word_counts.most_common(2))
# Output: [('python', 4), ('is', 3)]

# 2. Grouping students by grade using defaultdict (no KeyError checks needed)
student_records = [
    ("Rahul", "A"), ("Pooja", "B"), ("Ayan", "A"), 
    ("Sneha", "C"), ("Sayan", "A"), ("Riya", "B")
]

grouped_students = defaultdict(list)
for name, grade in student_records:
    grouped_students[grade].append(name)

print("Grouped by Grade:", dict(grouped_students))
# Output: {'A': ['Rahul', 'Ayan', 'Sayan'], 'B': ['Pooja', 'Riya'], 'C': ['Sneha']}

# 3. Sorting a dictionary by value (Descending order)
marks = {"Math": 88, "Physics": 95, "Chemistry": 79, "Computer": 99}
sorted_marks = dict(sorted(marks.items(), key=lambda item: item[1], reverse=True))
print("Ranked Subjects:", sorted_marks)
# Output: {'Computer': 99, 'Physics': 95, 'Math': 88, 'Chemistry': 79}

3. Regular Expressions (regex) for Real Data Cleansing

import re

text = """
Contact support at info@pragatiskill.org or admissions@pragati.edu.in.
Hotlines: +91-8016363962, +91 7605895571, or call 03220-255900.
Office PIN Code: 721433.
"""

# Extract all valid email addresses
emails = re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', text)
print("Extracted Emails:", emails)

# Extract Indian 10-digit phone numbers
phones = re.findall(r'(?:\+91[\s-]?)?[6-9]\d{9}', text)
print("Extracted Mobile Numbers:", phones)

# Sanitize HTML tags out of raw scrapings
raw_html = "

Learn Python in Kolkata!

" clean_text = re.sub(r'<[^>]+>', '', raw_html) print("Cleaned Text:", clean_text) # Learn Python in Kolkata!

Module 3: Real-World OOP with Encapsulation & Design Patterns

Production-Grade Bank Account Management System

from datetime import datetime
from abc import ABC, abstractmethod

# Abstract Base Class enforcing contract
class TransactionRecord(ABC):
    @abstractmethod
    def log_transaction(self, tx_type: str, amount: float):
        pass

class BankAccount(TransactionRecord):
    # Class attribute (shared by all instances)
    BANK_NAME = "Pragati Central Bank"
    INTEREST_RATE = 4.5  # Annual percentage

    def __init__(self, account_holder: str, initial_balance: float = 0.0):
        self.holder = account_holder
        self.__balance = float(initial_balance)  # Private attribute (Encapsulated)
        self._history: list[dict] = []          # Protected attribute
        self.log_transaction("ACCOUNT_OPENING", self.__balance)

    # Getter property
    @property
    def balance(self) -> float:
        return self.__balance

    def deposit(self, amount: float) -> bool:
        if amount <= 0:
            raise ValueError("Deposit amount must be strictly greater than zero.")
        self.__balance += amount
        self.log_transaction("DEPOSIT", amount)
        return True

    def withdraw(self, amount: float) -> bool:
        if amount <= 0:
            raise ValueError("Withdrawal amount must be greater than zero.")
        if amount > self.__balance:
            raise ValueError(f"Insufficient funds! Current balance: ₹{self.__balance:,.2f}")
        self.__balance -= amount
        self.log_transaction("WITHDRAWAL", -amount)
        return True

    def log_transaction(self, tx_type: str, amount: float):
        self._history.append({
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "type": tx_type,
            "amount": amount,
            "resulting_balance": self.__balance
        })

    def print_statement(self):
        print(f"\n--- Statement for {self.holder} ({self.BANK_NAME}) ---")
        for tx in self._history:
            print(f"[{tx['timestamp']}] {tx['type']:<15} | Amount: ₹{tx['amount']:>10,.2f} | Balance: ₹{tx['resulting_balance']:>10,.2f}")

    # Magic / Dunder method for representation
    def __repr__(self) -> str:
        return f"BankAccount(holder='{self.holder}', balance={self.__balance})"

    def __len__(self) -> int:
        return len(self._history)

# Testing the OOP System
acc = BankAccount("Souvik Jana", 5000.0)
acc.deposit(12500.0)
acc.withdraw(3200.0)
acc.print_statement()
print(f"Total Transactions Recorded: {len(acc)}")

Module 4: Real-World Database Integration (SQLite3 Built-in)

Python comes with a built-in production relational SQL engine (sqlite3). You can run complete ACID transactions without installing external servers:

import sqlite3

def init_database():
    # Connect to SQLite file (creates it if it doesn't exist)
    conn = sqlite3.connect("pragati_students.db")
    cursor = conn.cursor()

    # Create table with constraints
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS enrollments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        roll_no TEXT UNIQUE NOT NULL,
        student_name TEXT NOT NULL,
        course_name TEXT NOT NULL,
        fee_paid REAL NOT NULL,
        city TEXT NOT NULL,
        enrolled_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    """)
    conn.commit()
    conn.close()

def insert_student(roll_no: str, name: str, course: str, fee: float, city: str):
    conn = sqlite3.connect("pragati_students.db")
    cursor = conn.cursor()
    try:
        # Parameterized query: 100% protection against SQL Injection
        cursor.execute("""
        INSERT INTO enrollments (roll_no, student_name, course_name, fee_paid, city)
        VALUES (?, ?, ?, ?, ?)
        """, (roll_no, name, course, fee, city))
        conn.commit()
        print(f"Successfully enrolled: {name} ({roll_no})")
    except sqlite3.IntegrityError:
        print(f"Error: Roll number {roll_no} already exists!")
    finally:
        conn.close()

def query_high_fee_students(min_fee: float) -> list[dict]:
    conn = sqlite3.connect("pragati_students.db")
    conn.row_factory = sqlite3.Row  # Returns rows as dictionary-like objects
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM enrollments WHERE fee_paid >= ? ORDER BY fee_paid DESC", (min_fee,))
    records = [dict(row) for row in cursor.fetchall()]
    conn.close()
    return records

# Running the database workflow
init_database()
insert_student("PSA-2026-001", "Ananya Das", "Full Stack Web Development", 8999.0, "Kolkata")
insert_student("PSA-2026-002", "Bikram Roy", "Tally Prime with GST", 3499.0, "Howrah")
insert_student("PSA-2026-003", "Tanmay Samanta", "Python Data Science", 7999.0, "Ramnagar")

print("\n--- Students with Fee >= ₹5,000 ---")
for s in query_high_fee_students(5000.0):
    print(f"{s['roll_no']}: {s['student_name']} -> {s['course_name']} (₹{s['fee_paid']:,.2f}) [{s['city']}]")

Module 5: Web Scraping & HTTP Automation (Requests & BeautifulSoup)

Automate market research, price comparisons, and data harvesting across the internet:

import requests
from bs4 import BeautifulSoup
import json

def scrape_educational_quotes() -> list[dict]:
    url = "https://quotes.toscrape.com/"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    }

    response = requests.get(url, headers=headers, timeout=10)
    if response.status_code != 200:
        print(f"Failed to fetch page. HTTP Status: {response.status_code}")
        return []

    soup = BeautifulSoup(response.text, "html.parser")
    quotes_data = []

    # Find all quote cards
    quote_blocks = soup.find_all("div", class_="quote")
    for block in quote_blocks:
        text = block.find("span", class_="text").get_text(strip=True)
        author = block.find("small", class_="author").get_text(strip=True)
        tags = [t.get_text(strip=True) for t in block.find_all("a", class_="tag")]

        quotes_data.append({
            "quote": text,
            "author": author,
            "tags": tags
        })

    return quotes_data

# Run and save to JSON file
scraped = scrape_educational_quotes()
print(f"Successfully scraped {len(scraped)} items.")
with open("scraped_quotes.json", "w", encoding="utf-8") as f:
    json.dump(scraped[:3], f, indent=4, ensure_ascii=False)
print("Saved top 3 sample items to scraped_quotes.json")

Module 6: Building a Real REST API Backend with FastAPI

Modern industry backends favor FastAPI over legacy frameworks because it offers asynchronous execution, automatic Swagger documentation, and Pydantic type validation:

# Save this file as: main.py
# Run with: uvicorn main:app --reload

from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field
from typing import Optional

app = FastAPI(title="Pragati Skill Academy Course API", version="2.0.0")

# In-memory database simulation
DATABASE = {
    "dca": {"title": "DCA (Diploma in Computer Application)", "fee": 4999.0, "duration": "6 Months"},
    "tally": {"title": "Tally Prime with GST", "fee": 3499.0, "duration": "3 Months"},
    "python": {"title": "Python Programming Masterclass", "fee": 4999.0, "duration": "3 Months"}
}

# Pydantic schema for strict payload validation
class CourseSchema(BaseModel):
    title: str = Field(..., min_length=3, example="Full Stack Development")
    fee: float = Field(..., gt=0, example=8999.0)
    duration: str = Field(default="3 Months", example="6 Months")

@app.get("/api/courses", status_code=status.HTTP_200_OK)
def list_all_courses():
    return {"total": len(DATABASE), "courses": DATABASE}

@app.get("/api/courses/{slug}", status_code=status.HTTP_200_OK)
def get_single_course(slug: str):
    clean_slug = slug.lower().strip()
    if clean_slug not in DATABASE:
        raise HTTPException(status_code=404, detail=f"Course with slug '{slug}' not found.")
    return {"slug": clean_slug, "data": DATABASE[clean_slug]}

@app.post("/api/courses", status_code=status.HTTP_201_CREATED)
def create_course(slug: str, course: CourseSchema):
    clean_slug = slug.lower().strip()
    if clean_slug in DATABASE:
        raise HTTPException(status_code=400, detail="Course slug already exists.")
    DATABASE[clean_slug] = course.model_dump()
    return {"message": "Course registered successfully", "slug": clean_slug, "course": DATABASE[clean_slug]}

Module 7: Practical System Automation Scripts

1. Batch File Renamer (Clean up messy downloads/photos in seconds)

import os
from pathlib import Path

def batch_rename_files(directory_path: str, prefix: str = "DOC_2026_"):
    target_dir = Path(directory_path)
    if not target_dir.exists():
        print("Directory does not exist.")
        return

    files = [f for f in target_dir.iterdir() if f.is_file()]
    # Sort files by modification date
    files.sort(key=lambda f: f.stat().st_mtime)

    for index, file_path in enumerate(files, start=1):
        extension = file_path.suffix
        new_filename = f"{prefix}{index:03d}{extension}"
        new_destination = target_dir / new_filename
        
        file_path.rename(new_destination)
        print(f"Renamed: {file_path.name} -> {new_filename}")

# Usage: batch_rename_files("C:/Users/Pragati/Downloads/Scans", "STUDENT_RECORD_")

2. Automated Email Notification with Attachments (smtplib)

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_dispatch_notification(recipient_email: str, student_name: str, tracking_number: str):
    smtp_server = "smtp.gmail.com"
    smtp_port = 587
    sender_email = "admin@pragatiskill.org"
    sender_password = "your_app_password_here"  # Use Google App Passwords

    msg = MIMEMultipart()
    msg['From'] = f"Pragati Skill Academy <{sender_email}>"
    msg['To'] = recipient_email
    msg['Subject'] = f"Certificate Dispatched via Speed Post - {student_name}"

    html_content = f"""
    
        
            

Congratulations, {student_name}!

Your official ISO 9001:2015 & E-Max India certified diploma has been printed, laminated, and dispatched via India Post Speed Post.

Tracking Consignment Number: {tracking_number}

Track your delivery in real-time at: indiapost.gov.in


Regards,
Examination Department
Pragati Skill Academy

""" msg.attach(MIMEText(html_content, 'html')) try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() # Upgrade to secure TLS encryption server.login(sender_email, sender_password) server.send_message(msg) print(f"Email sent successfully to {recipient_email}") except Exception as e: print(f"Failed to send email: {e}") finally: server.quit()

Module 8: Top 5 Real Coding Interview Problems Solved with Optimal Complexity

1. Two Sum (LeetCode #1) — O(N) Time, O(N) Space

Given an array of integers and a target sum, return indices of the two numbers that add up to target.

def two_sum(nums: list[int], target: int) -> list[int]:
    seen = {}  # val -> index mapping
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

print("Two Sum [2, 7, 11, 15], target 9:", two_sum([2, 7, 11, 15], 9))  # [0, 1]

2. Valid Parentheses (LeetCode #20) — O(N) Time, O(N) Space

Determine if input string of brackets '()[]{}' is valid using a Stack.

def is_valid_parentheses(s: str) -> bool:
    stack = []
    pairs = {')': '(', '}': '{', ']': '['}
    for char in s:
        if char in pairs.values():
            stack.append(char)
        elif char in pairs:
            if not stack or stack.pop() != pairs[char]:
                return False
    return len(stack) == 0

print("Valid '({[]})':", is_valid_parentheses("({[]})"))  # True
print("Invalid '([)]':", is_valid_parentheses("([)]"))    # False

3. Binary Search — O(log N) Time, O(1) Space

Search a sorted array in logarithmic time by repeatedly dividing search space in half.

def binary_search(sorted_arr: list[int], target: int) -> int:
    left, right = 0, len(sorted_arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if sorted_arr[mid] == target:
            return mid
        elif sorted_arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

numbers = [11, 22, 33, 44, 55, 66, 77, 88, 99]
print("Index of 55:", binary_search(numbers, 55))  # 4
print("Index of 100:", binary_search(numbers, 100)) # -1
🎁 Free Career Guidance & Demo Session

Get Free Syllabus PDF & 2-Day Live Demo Class

Connect with our certified academic counselors today. Understand module details, installment fee plans, and how students from your area are building successful careers.

Frequently Asked Questions

What is the difference between a List and a Tuple in Python?
Lists are mutable (can be changed, items appended or removed) and use square brackets []. Tuples are immutable (cannot be altered after creation) and use parentheses ().
What does 'yield' do in Python?
The 'yield' keyword turns a function into a generator. Instead of returning all items at once in memory, it pauses execution and yields values one at a time, conserving RAM on massive datasets.
What is the purpose of virtual environments (venv)?
A virtual environment creates an isolated folder containing its own Python binaries and pip libraries, preventing version conflicts between different projects on the same machine.

Student Reviews

"Pragati Skill Academy-তে DCA course করে আমি সরকারি চাকরির পরীক্ষায় ভালো ফল করেছি। Teachers অনেক helpful এবং practical training চমৎকার।"

Sourav Maity

"Tally Prime course আমার career completely change করে দিয়েছে। এখন আমি একটি private firm-এ Accountant হিসেবে কাজ করছি। Thank you Pragati Skill Academy!"

Priya Das

"Computer basic course থেকে শুরু করে এখন আমি Graphic Design শিখছি। সবকিছু step by step শেখানো হয়। Very good institute!"

Rahul Mondal

"ADCA course-এর syllabus অনেক comprehensive। MS Office, Tally, Web Design সব একসাথে শেখা যায়। Best computer center in this area."

Ananya Samanta

Check Batch Availability & Certificate Delivery by PIN Code

Instant lookup for all 19,000+ Indian PIN Codes, Blocks, and Villages

Speed Post Delivery Timeline 24 - 48 Hours via Speed Post
Available Training Mode Classroom Lab & Online Hybrid
Govt Recognized Certificate ISO 9001:2015 & E-Max India
Admissions open for immediate batch starting this week. Inquire on WhatsApp for PIN 721433