0% found this document useful (0 votes)
13 views24 pages

MITS Python Programming Ebook

The MITS Academy Python Programming Course provides a comprehensive curriculum covering Python basics to intermediate concepts, including data types, control flow, and functions. It emphasizes practical applications, such as automating workflows and data management, with hands-on coding examples. The course is designed for learners to build a strong foundation in Python programming, suitable for various real-world scenarios.

Uploaded by

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

MITS Python Programming Ebook

The MITS Academy Python Programming Course provides a comprehensive curriculum covering Python basics to intermediate concepts, including data types, control flow, and functions. It emphasizes practical applications, such as automating workflows and data management, with hands-on coding examples. The course is designed for learners to build a strong foundation in Python programming, suitable for various real-world scenarios.

Uploaded by

bhumikatalwar19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MITS Academy — Python Programming Course

MITS ACADEMY
Python Programming Course

Basic to Intermediate | Ebook-Style Curriculum with Code Examples | MITS


Academy
[Link]

Page 1 | MITS Academy | [Link]


MITS Academy — Python Programming Course

Module 1: Python Basics — Setting the Foundation


1.1 What is Python and Why Learn It?
Python is a high-level, interpreted, general-purpose programming language created by Guido
van Rossum and released in 1991. Today it is the world's most popular language (TIOBE Index,
Stack Overflow Survey). Google, Instagram, Netflix, NASA, and every major financial institution
use Python.
Python's philosophy — readable, concise, explicit code — makes it the ideal first language and
an extremely productive expert tool. A Python script can do in 10 lines what takes 50 lines in
Java, without sacrificing clarity.

Real-World Context
An e-commerce company's analyst spent 2 hours every morning downloading sales reports,
computing totals in Excel, and emailing summaries. A Python script automated this entire
workflow to run in 12 seconds — saving 40 hours a month. That is the practical value of Python.

1.2 Setting Up Python and VS Code


Download Python 3.11+ from [Link]. On Windows, tick "Add Python to PATH" during
installation — without this Python won't run from the terminal. Verify by opening a terminal and
running: python --version. Install VS Code and the Microsoft Python extension. For managing
project-specific dependencies, always create a virtual environment: python -m venv venv, then
activate it.
# Verify your setup
import sys
print([Link]) # e.g. 3.11.4
print([Link]) # path to Python binary

# Your first real program


name = input("What is your name? ")
print(f"Hello {name}! Welcome to Python.")

# Run: python [Link]

1.3 Variables, Data Types, and Type Conversion


A variable is a named container in memory. Python is dynamically typed — you never declare a
type; Python infers it from the assigned value. The core data types are: int (whole numbers),
float (decimal numbers), str (text), bool (True/False), and NoneType (absence of value).
Type conversion is essential because user input always arrives as a string even if the user
types a number. Use int(), float(), str() to convert explicitly. Implicit conversion happens
automatically in safe situations — adding an int and a float gives a float.
# Variables and types
student_name = "Rahul Sharma" # str
age = 21 # int
cgpa = 8.75 # float
is_enrolled = True # bool
fees_pending = None # NoneType

print(type(student_name)) # <class 'str'>

Page 2 | MITS Academy | [Link]


MITS Academy — Python Programming Course

print(type(age)) # <class 'int'>

# Type conversion — critical for user input


raw_age = input("Enter age: ") # always returns str
age = int(raw_age) # convert to int
price_str = "299.99"
price = float(price_str) # 299.99

# f-string formatting (preferred modern approach)


print(f"Student {student_name}, age {age}, CGPA {cgpa:.2f}")
# Output: Student Rahul Sharma, age 21, CGPA 8.75

# Checking types
print(isinstance(cgpa, float)) # True
print(isinstance(age, (int, float))) # True — multiple types

1.4 Strings — Working with Text Data


Strings are sequences of characters. In real applications strings represent user names, emails,
product descriptions, API responses, SQL queries, log messages, and HTML content. Python
provides 40+ built-in string methods.
Key concepts: strings are immutable (you cannot change a character in place; you must create
a new string). String indexing is zero-based. Slicing [start:stop:step] extracts substrings without
loops.
# String creation
full_name = "Ananya Krishnan"
city = 'Bengaluru'
multiline = """Line 1
Line 2
Line 3"""

# Indexing and slicing


print(full_name[0]) # A (first char)
print(full_name[-1]) # n (last char)
print(full_name[0:6]) # Ananya (index 0 to 5)
print(full_name[::2]) # AayKihn (every 2nd char)
print(full_name[::-1]) # nahrK aynanA (reversed!)

# Essential methods
text = " Hello, Python World! "
print([Link]()) # remove leading/trailing whitespace
print([Link]()) # ALL CAPS
print([Link]()) # all lower
print([Link]("Python", "Beautiful"))
print([Link](",")) # [' Hello', ' Python World! ']
print([Link]("l")) # 3
print("python" in [Link]()) # True

# f-string formatting (Python 3.6+)


name = "Rohan"
marks = 87.5
print(f"Student {name} scored {marks:.2f}%")
print(f"{'Pass' if marks >= 40 else 'Fail'}") # inline if

# Real-world: email validation


email = "user@[Link]"
is_valid = "@" in email and "." in [Link]("@")[-1]
domain = [Link]("@")[1] # [Link]
username = [Link]("@")[0] # user

Page 3 | MITS Academy | [Link]


MITS Academy — Python Programming Course

print(f"Valid: {is_valid}, Domain: {domain}")

1.5 Lists — Ordered, Mutable Collections


A list is an ordered, mutable (changeable) sequence. It can hold any mix of types. Lists are the
most-used Python data structure — shopping carts, student rolls, transaction logs, API
response arrays. Any time you have a collection of items in a sequence, use a list.
# Creating and accessing lists
fruits = ["apple", "banana", "mango", "orange"]
marks = [88, 92, 76, 95, 83]
mixed = [1, "hello", 3.14, True, None]

print(fruits[0]) # apple
print(fruits[-1]) # orange
print(fruits[1:3]) # ['banana', 'mango']

# Modifying lists
[Link]("grapes") # add to end
[Link](1, "kiwi") # insert at index
[Link]("banana") # remove first match
last = [Link]() # remove + return last
fruits[0] = "pineapple" # update by index

# Useful operations
print(len(fruits)) # length
print("mango" in fruits) # membership test
sorted_marks = sorted(marks, reverse=True)
[Link]() # sort in-place

# List comprehension (Pythonic, fast)


squares = [x**2 for x in range(1, 6)]
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
names_upper = [[Link]() for n in ["priya", "arjun", "meena"]]

# Real-world: shopping cart


cart = []
[Link]({"item": "Laptop", "price": 45000, "qty": 1})
[Link]({"item": "Mouse", "price": 599, "qty": 2})
[Link]({"item": "Keyboard", "price": 1299, "qty": 1})

total = sum(item["price"] * item["qty"] for item in cart)


print(f"Cart total: Rs.{total:,}") # Rs.47,497

1.6 Tuples, Sets, and Dictionaries


Tuples are immutable sequences — use them for data that must not change: GPS coordinates,
RGB colors, database row fields. Immutability makes tuples safer and slightly faster than lists.
Sets are unordered collections of unique values — perfect for removing duplicates, and
membership testing is O(1) unlike lists which are O(n). Dictionaries map unique keys to values
— the most important data structure in Python for representing real-world entities like users,
products, and API responses.
# TUPLES — immutable
delhi_coords = (28.6139, 77.2090) # latitude, longitude
rgb_red = (255, 0, 0)
print(delhi_coords[0]) # 28.6139
# delhi_coords[0] = 1.0 # TypeError — cannot modify!

# tuple unpacking

Page 4 | MITS Academy | [Link]


MITS Academy — Python Programming Course

lat, lon = delhi_coords


print(f"Lat: {lat}, Lon: {lon}")

# SETS — unique, unordered


attendance = {"Priya", "Arjun", "Priya", "Meena", "Arjun"}
print(attendance) # {'Priya', 'Arjun', 'Meena'} — duplicates gone

# Set operations (like Venn diagrams)


cs_students = {"Priya", "Arjun", "Dev"}
ml_students = {"Arjun", "Meena", "Dev"}
both = cs_students & ml_students # intersection
either = cs_students | ml_students # union
only_cs = cs_students - ml_students # difference
print(both) # {'Arjun', 'Dev'}

# DICTIONARIES — key-value pairs


student = {
"name": "Vikram Singh",
"age": 22,
"cgpa": 8.9,
"courses": ["Python", "ML", "SQL"]
}

print(student["name"]) # Vikram Singh


print([Link]("phone", "N/A")) # N/A (safe access with default)
student["email"] = "vikram@[Link]" # add key
student["age"] = 23 # update key
del student["age"] # delete key

# Iterating
for key, value in [Link]():
print(f" {key}: {value}")

# Dict comprehension
price_map = {"Laptop": 45000, "Phone": 15000, "Tablet": 25000}
discounted = {item: price * 0.9 for item, price in price_map.items()}
print(discounted) # {'Laptop': 40500.0, 'Phone': 13500.0, 'Tablet': 22500.0}

Module 2: Control Flow and Functions


2.1 Conditional Statements
If-elif-else lets programs make decisions. Python uses indentation (4 spaces) instead of curly
braces to define code blocks — this enforces readable code. Think of conditionals as the
decision tree your program walks through at runtime.
# Grade calculator
marks = int(input("Enter marks (0-100): "))

if marks >= 90:


grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 40:
grade = "D"
else:

Page 5 | MITS Academy | [Link]


MITS Academy — Python Programming Course

grade = "F"

print(f"Grade: {grade}")

# Logical operators
age = 20
has_id = True
is_adult = age >= 18 and has_id
print("Entry allowed" if is_adult else "Entry denied")

# Ternary expression
status = "Pass" if marks >= 40 else "Fail"

# Real-world: e-commerce discount engine


cart_value = 2500
is_premium = True
coupon_code = "SAVE10"

if is_premium and cart_value > 2000:


discount = 0.15
elif coupon_code == "SAVE10":
discount = 0.10
elif cart_value > 1000:
discount = 0.05
else:
discount = 0

final_price = cart_value * (1 - discount)


print(f"Discount: {discount*100:.0f}% | Final: Rs.{final_price:.2f}")

2.2 Loops — for and while


Loops execute a block of code repeatedly. The for loop iterates over a sequence (list, tuple,
string, range). The while loop repeats as long as a condition is True. Use for when you know the
number of iterations; use while when you don't.
# FOR LOOP
students = ["Priya", "Arjun", "Meena", "Ravi"]
for student in students:
print(f"Hello, {student}!")

# range(start, stop, step)


for i in range(1, 11, 2): # 1 3 5 7 9
print(i, end=" ")

# enumerate — get index AND value


for idx, student in enumerate(students, start=1):
print(f"{idx}. {student}")

# zip — iterate two lists together


names = ["Priya", "Arjun", "Meena"]
scores = [88, 95, 76]
for name, score in zip(names, scores):
print(f"{name}: {score}")

# WHILE LOOP — PIN verification


MAX_ATTEMPTS = 3
CORRECT_PIN = "1234"
attempts = 0

while attempts < MAX_ATTEMPTS:

Page 6 | MITS Academy | [Link]


MITS Academy — Python Programming Course

pin = input("Enter PIN: ")


if pin == CORRECT_PIN:
print("Access granted!")
break
attempts += 1
print(f"Wrong. {MAX_ATTEMPTS - attempts} attempts left.")
else:
print("Account locked.")

# Loop control
for num in range(1, 20):
if num % 2 == 0:
continue # skip even
if num > 9:
break # stop after 9
print(num) # 1 3 5 7 9

2.3 Functions — Reusable Building Blocks


A function is a named, reusable block of code. Functions are the single most important tool for
writing maintainable code. The DRY principle (Don't Repeat Yourself) — if you write the same
logic more than once, put it in a function. Functions have parameters (what they accept) and a
return value (what they produce).
# Basic function
def greet(name, greeting="Hello"):
"""Return a personalised greeting.

Args:
name: The person's name (str)
greeting: Opening word (str, default "Hello")
Returns:
Formatted greeting string
"""
return f"{greeting}, {name}! Welcome to MITS Academy."

print(greet("Ananya")) # Hello, Ananya! ...


print(greet("Ravi", "Good morning")) # Good morning, Ravi! ...

# Multiple return values (actually a tuple)


def min_max_avg(numbers):
return min(numbers), max(numbers), sum(numbers)/len(numbers)

lo, hi, avg = min_max_avg([88, 92, 76, 95, 83])


print(f"Min:{lo} Max:{hi} Avg:{avg:.1f}")

# *args — variable positional arguments


def total_cost(*prices):
return sum(prices)

print(total_cost(100, 200, 350, 99)) # 749

# **kwargs — variable keyword arguments


def create_profile(**info):
for key, val in [Link]():
print(f" {key}: {val}")

create_profile(name="Rahul", age=22, city="Delhi", course="Python")

# Real-world: EMI calculator


def emi(principal, annual_rate, months):

Page 7 | MITS Academy | [Link]


MITS Academy — Python Programming Course

"""Calculate monthly EMI.

Real banks use this exact formula (reducing balance method).


"""
if annual_rate == 0:
return principal / months
r = annual_rate / (12 * 100) # monthly interest rate
emi_amount = principal * r * (1+r)**months / ((1+r)**months - 1)
return round(emi_amount, 2)

loan = emi(500000, 8.5, 60)


print(f"Monthly EMI on Rs.5L @ 8.5% for 5 years: Rs.{loan}")

2.4 Lambda, map, filter, and List Comprehensions


Lambda functions are anonymous one-line functions — ideal for short throwaway operations.
map() applies a function to every element of an iterable. filter() keeps only elements where the
function returns True. reduce() reduces a list to a single value. These functional tools, combined
with list comprehensions, make Python code concise and expressive.
import functools

# Lambda syntax: lambda parameters: expression


square = lambda x: x ** 2
add = lambda x, y: x + y
print(square(5)) # 25
print(add(3, 7)) # 10

# sorted() with lambda key


students = [
{"name": "Priya", "marks": 88},
{"name": "Arjun", "marks": 95},
{"name": "Meena", "marks": 76},
]
top_first = sorted(students, key=lambda s: s["marks"], reverse=True)

# map() — transform every element


prices = [100, 200, 300, 400, 500]
with_gst = list(map(lambda p: round(p * 1.18, 2), prices))
print(with_gst) # [118.0, 236.0, ...]

# filter() — keep elements matching condition


salaries = [25000, 55000, 42000, 80000, 30000]
high_pay = list(filter(lambda s: s > 50000, salaries))

# reduce() — accumulate to single value


total = [Link](lambda a, b: a + b, prices)

# LIST COMPREHENSIONS (preferred over map/filter in most cases)


squares = [x**2 for x in range(1, 6)]
even_sq = [x**2 for x in range(1, 11) if x % 2 == 0]
passed_students = [n for n, m in [("Priya",88),("Dev",35)] if m>=40]

# Nested comprehension — flatten 2D list


matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [n for row in matrix for n in row]

# Dict comprehension
word_lengths = {word: len(word) for word in ["Python","Java","C++"]}
print(word_lengths) # {'Python': 6, 'Java': 4, 'C++': 3}

Page 8 | MITS Academy | [Link]


MITS Academy — Python Programming Course

Module 3: Object-Oriented Programming in Python


3.1 Classes and Objects
OOP organises code around objects that bundle data (attributes) and behaviour (methods). This
mirrors the real world: a bank account has a balance (data) and can deposit, withdraw, and
show a statement (behaviour). OOP makes large codebases manageable, testable, and
extensible.
A class is the blueprint. An object is a specific instance of that blueprint. Just as a house
blueprint can produce many different houses, a class can produce many different objects —
each with their own independent data.
class BankAccount:
"""Models a basic bank account — real banks use similar designs."""

bank_name = "MITS Bank" # class attribute (shared by all)

def __init__(self, holder, initial=0):


"""Constructor — runs automatically when object is created."""
[Link] = holder # instance attributes
[Link] = initial
[Link] = []

def deposit(self, amount):


if amount <= 0:
raise ValueError("Amount must be positive")
[Link] += amount
[Link](f"+{amount} (deposit)")
print(f"Rs.{amount} deposited. Balance: Rs.{[Link]}")

def withdraw(self, amount):


if amount > [Link]:
print("Insufficient funds!")
return False
[Link] -= amount
[Link](f"-{amount} (withdrawal)")
return True

def statement(self):
print(f"--- {self.bank_name} | {[Link]} ---")
for t in [Link]:
print(f" {t}")
print(f" Balance: Rs.{[Link]}")

def __str__(self): # called by print()


return f"Account({[Link]}, Rs.{[Link]})"

def __repr__(self): # called in REPL / debugging


return f"BankAccount(holder={[Link]!r}, balance={[Link]})"

# Using the class


acc1 = BankAccount("Priya Sharma", 10000)
acc2 = BankAccount("Arjun Mehta")

[Link](5000)
[Link](3000)
[Link]()
print(acc1) # BankAccount's __str__
print(BankAccount.bank_name) # class attribute via class name

Page 9 | MITS Academy | [Link]


MITS Academy — Python Programming Course

3.2 Inheritance and Polymorphism


Inheritance allows a child class to inherit all attributes and methods from a parent class, then
add or override as needed. This encodes the "is-a" relationship: a SavingsAccount IS-A
BankAccount. Polymorphism means different classes respond to the same method name in
their own way — sort of a universal remote control for objects.
# Parent class
class BankAccount:
def __init__(self, holder, balance=0):
[Link] = holder
[Link] = balance

def deposit(self, amount):


[Link] += amount

def withdraw(self, amount):


[Link] -= amount

def __str__(self):
return f"{[Link]}: Rs.{[Link]:,}"

# Child: SavingsAccount
class SavingsAccount(BankAccount):
MIN_BALANCE = 1000
INTEREST_RATE = 0.04 # 4% per year

def __init__(self, holder, balance=0):


super().__init__(holder, balance) # call parent init

def withdraw(self, amount): # OVERRIDE parent method


if [Link] - amount < self.MIN_BALANCE:
print(f"Min balance Rs.{self.MIN_BALANCE} required!")
return
super().withdraw(amount)

def credit_interest(self): # NEW method


interest = [Link] * self.INTEREST_RATE
[Link] += interest
print(f"Interest Rs.{interest:.2f} credited")

# Child: LoanAccount
class LoanAccount(BankAccount):
def __init__(self, holder, loan_amount, rate):
super().__init__(holder, -loan_amount) # negative balance = debt
[Link] = rate

def monthly_payment(self):
return round(abs([Link]) * [Link] / 12, 2)

def __str__(self):
return f"{[Link]}: Loan Rs.{abs([Link]):,}"

# Polymorphism — same method name, different behaviour


accounts = [
SavingsAccount("Priya", 15000),
LoanAccount("Arjun", 200000, 0.085),
BankAccount("Meena", 8000)
]
for acc in accounts:
print(acc) # each class's __str__ is called automatically

Page 10 | MITS Academy | [Link]


MITS Academy — Python Programming Course

3.3 Encapsulation, Properties, and Abstract Classes


Encapsulation hides internal implementation behind a public interface. In Python, prefix
attributes with double underscore (__) to make them private. The @property decorator provides
controlled, Pythonic access to private attributes without Java-style getter/setter verbosity.
from abc import ABC, abstractmethod

# Encapsulation with @property


class Employee:
def __init__(self, name, salary):
[Link] = name
self.__salary = salary # private

@property
def salary(self): # getter
return self.__salary

@[Link]
def salary(self, amount): # setter with validation
if amount < 15000:
raise ValueError("Salary below minimum wage!")
self.__salary = amount

@property
def annual_ctc(self): # computed property (read-only)
return self.__salary * 12

emp = Employee("Priya", 50000)


print([Link]) # 50000 (via getter)
[Link] = 55000 # via setter
print(emp.annual_ctc) # 660000
# emp.__salary # AttributeError — private!

# Abstract Base Class — enforce interface across subclasses


class Shape(ABC):
@abstractmethod
def area(self): pass

@abstractmethod
def perimeter(self): pass

def describe(self): # concrete method (shared)


print(f"{type(self).__name__}: area={[Link]():.2f}")

class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14159 * self.r ** 2
def perimeter(self):
return 2 * 3.14159 * self.r

class Rectangle(Shape):
def __init__(self, l, w):
self.l, self.w = l, w
def area(self):
return self.l * self.w
def perimeter(self):
return 2 * (self.l + self.w)

Page 11 | MITS Academy | [Link]


MITS Academy — Python Programming Course

# Polymorphism in action
for shape in [Circle(5), Rectangle(4, 6), Circle(3)]:
[Link]()
# shape = Shape() # TypeError — cannot instantiate abstract class

Module 4: File Handling and Exception Management


4.1 Working with Files
Almost every production application reads from or writes to files: config files, log files, data
exports, reports. Always use the with statement (context manager) — it automatically closes the
file even if an error occurs, preventing data corruption and resource leaks.
import csv, json
from pathlib import Path

# WRITING text
with open("[Link]", "w", encoding="utf-8") as f:
[Link]("Name,Marks,Grade
")
[Link]("Priya,88,A
")
[Link]("Arjun,95,A+
")
# File automatically closed after the with block

# READING entire file


with open("[Link]", "r", encoding="utf-8") as f:
content = [Link]() # full string

# READING line by line (memory-efficient for large files)


with open("[Link]", "r") as f:
header = [Link]() # first line
for line in f: # iterate remaining lines
name, marks, grade = [Link]().split(",")
print(f"{name} got grade {grade}")

# CSV with DictReader/DictWriter


data = [
{"Name":"Priya", "Marks":88, "Grade":"A"},
{"Name":"Arjun", "Marks":95, "Grade":"A+"},
]
with open("[Link]", "w", newline="") as f:
writer = [Link](f, fieldnames=["Name","Marks","Grade"])
[Link]()
[Link](data)

with open("[Link]") as f:
for row in [Link](f):
print(f"{row['Name']}: {row['Marks']}")

# JSON (common for APIs and configs)


config = {"api_key": "abc123", "max_records": 1000, "debug": False}
with open("[Link]", "w") as f:
[Link](config, f, indent=2)

with open("[Link]") as f:
loaded = [Link](f)
print(loaded["api_key"]) # abc123

Page 12 | MITS Academy | [Link]


MITS Academy — Python Programming Course

# pathlib — modern, OS-independent path handling


base = Path("data")
[Link](exist_ok=True)
report = base / "[Link]" # works on Windows and Linux
report.write_text("Monthly Report
...", encoding="utf-8")
print([Link]()) # True
print(list([Link]("*.txt"))) # all txt files

4.2 Exception Handling — Professional Error Management


Errors are inevitable; crashes are optional. Exception handling lets your program detect,
respond to, and recover from errors without crashing. Professional applications always
anticipate failure scenarios — missing files, invalid input, network timeouts, database errors.
# try-except-else-finally
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero")
return None
except TypeError as e:
print(f"Type error: {e}")
return None
else:
print("Calculation succeeded") # runs only if no exception
return result
finally:
print("divide() finished") # ALWAYS runs

print(divide(10, 2)) # 5.0


print(divide(10, 0)) # error message, None

# Custom exception classes


class AppError(Exception):
"""Base class for application errors."""
pass

class InsufficientFundsError(AppError):
def __init__(self, balance, requested):
[Link] = balance
[Link] = requested
super().__init__(
f"Cannot withdraw Rs.{requested:,}. "
f"Available: Rs.{balance:,}"
)

class InvalidAmountError(AppError):
pass

class BankAccount:
def __init__(self, balance):
[Link] = balance

def withdraw(self, amount):


if not isinstance(amount, (int, float)):
raise InvalidAmountError("Amount must be numeric")
if amount <= 0:
raise InvalidAmountError("Amount must be positive")
if amount > [Link]:

Page 13 | MITS Academy | [Link]


MITS Academy — Python Programming Course

raise InsufficientFundsError([Link], amount)


[Link] -= amount
return [Link]

# Structured error handling


acc = BankAccount(5000)
for test_amount in [1000, 8000, -500, "abc"]:
try:
new_bal = [Link](test_amount)
print(f"Withdrawn {test_amount}. Balance: Rs.{new_bal:,}")
except InsufficientFundsError as e:
print(f"[FUNDS ERROR] {e}")
except InvalidAmountError as e:
print(f"[INVALID] {e}")
except AppError as e:
print(f"[APP ERROR] {e}")

Module 5: NumPy and Pandas — Data Handling at


Scale
5.1 NumPy — Vectorised Numerical Computing
NumPy (Numerical Python) provides the ndarray — an N-dimensional array implemented in C
— that runs up to 100x faster than equivalent Python loops on large numeric datasets. Every
data science and ML library (Pandas, Scikit-learn, TensorFlow, PyTorch) uses NumPy arrays
internally.
import numpy as np

# Array creation
a = [Link]([1, 2, 3, 4, 5]) # 1D
m = [Link]([[1,2,3],[4,5,6]]) # 2D (matrix)
print([Link]) # (5,)
print([Link]) # (2, 3)
print([Link]) # int64

# Useful constructors
zeros = [Link]((3, 4))
ones = [Link]((2, 3))
eye = [Link](3) # identity matrix
rng = [Link](0, 10, 2) # [0 2 4 6 8]
ls = [Link](0, 1, 5) # 5 evenly spaced in [0,1]
rand = [Link](40, 100, 20) # 20 random marks

# Vectorised ops — NO explicit loops


prices = [Link]([100, 200, 300, 400, 500])
with_gst = prices * 1.18 # GST on all at once
discounted = prices * 0.9 # 10% off all

# Statistics
marks = [Link]([88, 92, 76, 95, 83, 71, 89])
print(f"Mean: {[Link](marks):.2f}")
print(f"Median: {[Link](marks)}")
print(f"Std: {[Link](marks):.2f}")
print(f"Pass %: {[Link](marks >= 40) * 100:.1f}%")

# Boolean indexing — filter without loops


high_scorers = marks[marks > 85] # [88 92 95 89]

Page 14 | MITS Academy | [Link]


MITS Academy — Python Programming Course

failed = marks[marks < 40]

# Matrix ops (core of ML)


A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])
print([Link](A, B)) # matrix multiply
print(A.T) # transpose
print([Link](A)) # determinant
vals, vecs = [Link](A) # eigenvalues — used in PCA

5.2 Pandas — Data Wrangling and Analysis


Pandas provides two key data structures: Series (1D labeled array — like a spreadsheet
column) and DataFrame (2D labeled table — like a full spreadsheet). Data scientists spend 60-
80% of their time cleaning and preparing data — Pandas is the primary tool for this. Master
Pandas and you become immediately productive in any data role.
import pandas as pd
import numpy as np

# Create DataFrame from dictionary


data = {
"Name": ["Priya","Arjun","Meena","Dev","Riya"],
"Dept": ["Sales","IT","Sales","HR","IT"],
"Salary": [45000, 75000, 48000, 35000, 82000],
"Experience": [3, 5, 2, 1, 6],
"City": ["Delhi","Mumbai","Delhi",None,"Bengaluru"]
}
df = [Link](data)

# Exploration
print([Link]) # (5, 5)
print([Link])
print([Link]()) # stats for numeric columns
print([Link]().sum()) # missing values per column

# Selection
print(df["Name"]) # Series
print(df[["Name","Salary"]]) # DataFrame
print([Link][0]) # row by integer index
print([Link][0, "Name"]) # specific cell
print([Link][1:3, 1:4]) # slice

# Filtering
high_earn = df[df["Salary"] > 50000]
it_team = df[df["Dept"] == "IT"]
senior_it = df[(df["Dept"]=="IT") & (df["Experience"]>=5)]

# Cleaning
df.drop_duplicates(inplace=True)
df["City"].fillna("Unknown", inplace=True)
df["Salary"] = df["Salary"].astype(float)
df["Name"] = df["Name"].[Link]().[Link]()

# Feature engineering
df["Annual_CTC"] = df["Salary"] * 12
df["Seniority"] = [Link](df["Experience"],
bins=[0,2,5,100],
labels=["Junior","Mid","Senior"])

# GroupBy and aggregation

Page 15 | MITS Academy | [Link]


MITS Academy — Python Programming Course

dept_summary = [Link]("Dept").agg(
avg_salary = ("Salary", "mean"),
headcount = ("Name", "count"),
max_exp = ("Experience", "max")
).reset_index().sort_values("avg_salary", ascending=False)
print(dept_summary)

# Pivot table — like Excel pivot


pivot = df.pivot_table(values="Salary", index="Dept",
columns="Seniority", aggfunc="mean")

# Merge (like SQL JOIN)


departments = [Link]({
"Dept": ["Sales","IT","HR"],
"Budget": [500000, 1200000, 300000]
})
merged = [Link](departments, on="Dept", how="left")

# Export
df.to_csv("[Link]", index=False)
df.to_excel("[Link]", index=False, sheet_name="Staff")

Module 6: Data Visualisation with Matplotlib and


Seaborn
6.1 Matplotlib — Full Control Plotting
Matplotlib is the foundation of Python's visualisation ecosystem. It offers pixel-level control over
every chart element. Understanding Matplotlib is essential because Seaborn, Pandas plotting,
and most other tools are built on it.
import [Link] as plt
import numpy as np

# --- Line chart: Revenue trend ---


months = ["Jan","Feb","Mar","Apr","May","Jun"]
revenue = [120000, 135000, 128000, 155000, 142000, 170000]

fig, ax = [Link](figsize=(10, 5))


[Link](months, revenue, marker="o", color="steelblue",
linewidth=2.5, markersize=8, label="Revenue 2024")
ax.fill_between(months, revenue, alpha=0.1, color="steelblue")
ax.set_title("Monthly Revenue — MITS Academy", fontsize=14, fontweight="bold")
ax.set_xlabel("Month"); ax.set_ylabel("Revenue (Rs.)")
[Link].set_major_formatter([Link](lambda x,_:
f"Rs.{x/1000:.0f}K"))
[Link](); [Link](True, alpha=0.3)
plt.tight_layout()
[Link]("[Link]", dpi=150)

# --- Subplots: bar + pie side by side ---


fig, (ax1, ax2) = [Link](1, 2, figsize=(12, 5))

# Bar chart
depts = ["Sales","IT","Marketing","HR"]
counts = [15, 30, 10, 8]
bars = [Link](depts, counts,
color=["#2196F3","#4CAF50","#FF9800","#9C27B0"])
ax1.bar_label(bars, padding=3)

Page 16 | MITS Academy | [Link]


MITS Academy — Python Programming Course

ax1.set_title("Headcount by Department")

# Pie chart
sizes = [35, 30, 20, 15]
labels = ["Python","Web Dev","Data Science","Others"]
[Link](sizes, labels=labels, autopct="%1.1f%%",
startangle=90, explode=[0.05]*4)
ax2.set_title("Course Enrollment")

plt.tight_layout()
[Link]()

# --- Histogram ---


marks = [Link](72, 12, 200)
[Link](figsize=(8, 5))
[Link](marks, bins=20, color="steelblue", edgecolor="white", alpha=0.8)
[Link]([Link](), color="red", linestyle="--",
label=f"Mean={[Link]():.1f}")
[Link]("Marks Distribution"); [Link]("Marks"); [Link]("Count")
[Link]()
[Link]()

6.2 Seaborn — Statistical Visualisation


Seaborn provides a high-level API over Matplotlib. It integrates directly with Pandas
DataFrames and automatically produces professional statistical charts with far less code. Use
Seaborn for exploratory data analysis and statistical storytelling.
import seaborn as sns
import [Link] as plt

sns.set_theme(style="whitegrid", palette="husl")
tips = sns.load_dataset("tips") # built-in dataset

# Scatter with regression


fig, axes = [Link](2, 2, figsize=(12, 10))

[Link](data=tips, x="total_bill", y="tip",


hue="sex", size="size", ax=axes[0,0])
axes[0,0].set_title("Tip vs Bill")

# Box plot — distribution + outliers


[Link](data=tips, x="day", y="total_bill",
hue="sex", ax=axes[0,1])
axes[0,1].set_title("Bill by Day & Gender")

# Violin plot — combines box + density


[Link](data=tips, x="day", y="tip",
inner="quartile", ax=axes[1,0])
axes[1,0].set_title("Tip Distribution by Day")

# Heatmap — correlations
corr = tips[["total_bill","tip","size"]].corr()
[Link](corr, annot=True, cmap="coolwarm",
fmt=".2f", ax=axes[1,1])
axes[1,1].set_title("Correlation Matrix")

plt.tight_layout()
[Link]()

# Pair plot — all relationships at once

Page 17 | MITS Academy | [Link]


MITS Academy — Python Programming Course

[Link](tips, hue="smoker", diag_kind="kde")


[Link]("Pairwise Relationships", y=1.02)
[Link]()

Module 7: Web Scraping and Automation


7.1 Web Scraping with requests and BeautifulSoup
Web scraping extracts data from websites programmatically. Use cases: price monitoring, job
board aggregation, research data collection, ML dataset building. Always check [Link] and
Terms of Service before scraping. Add delays between requests to be a polite bot.
import requests
from bs4 import BeautifulSoup
import time, csv

URL = "[Link] # safe practice site


HEADERS = {"User-Agent": "Mozilla/5.0 (Educational Python Bot)"}

def scrape_books(max_pages=3):
all_books = []

for page in range(1, max_pages + 1):


url = f"{URL}catalogue/page-{page}.html" if page > 1 else URL
response = [Link](url, headers=HEADERS, timeout=10)
response.raise_for_status() # raise exception if 4xx/5xx

soup = BeautifulSoup([Link], "[Link]")


books = soup.find_all("article", class_="product_pod")

for book in books:


title = book.h3.a["title"]
price = float([Link]("p", class_="price_color").text[1:])
rating_map = {"One":1,"Two":2,"Three":3,"Four":4,"Five":5}
rating = rating_map.get(book.p["class"][1], 0)
avail = "In stock" in [Link]("p", class_="availability").text

all_books.append({
"title": title, "price": price,
"rating": rating, "in_stock": avail
})

print(f"Page {page}: scraped {len(books)} books")


[Link](1) # polite delay

return all_books

books = scrape_books(max_pages=2)
[Link](key=lambda b: b["rating"], reverse=True)

# Save results
with open("[Link]", "w", newline="", encoding="utf-8") as f:
writer = [Link](f, fieldnames=books[0].keys())
[Link]()
[Link](books)
print(f"Saved {len(books)} books to [Link]")

Page 18 | MITS Academy | [Link]


MITS Academy — Python Programming Course

7.2 File and Email Automation


Python can automate tedious file organisation, report generation, and email sending. A Python
automation script running daily can save hours of manual work every week — a common task in
any business operation.
from pathlib import Path
import shutil, os, smtplib
from [Link] import MIMEMultipart
from [Link] import MIMEText

# Automatic file organiser


def organise_folder(folder_path):
CATEGORIES = {
"Images": {".jpg",".jpeg",".png",".gif",".svg",".webp"},
"Documents": {".pdf",".doc",".docx",".txt",".xlsx",".csv"},
"Videos": {".mp4",".avi",".mov",".mkv",".webm"},
"Code": {".py",".js",".html",".css",".java",".cpp"},
"Archives": {".zip",".rar",".7z",".tar",".gz"},
}
folder = Path(folder_path)
moved = 0
for file in [Link]():
if file.is_file():
ext = [Link]()
category = next(
(cat for cat, exts in [Link]() if ext in exts),
"Others"
)
dest = folder / category
[Link](exist_ok=True)
[Link](str(file), str(dest / [Link]))
moved += 1
print(f"Organised {moved} files")

# Auto email report


def send_report(to_email, subject, body_html):
SENDER = [Link]("EMAIL_USER") # store in env var
PASSWORD = [Link]("EMAIL_PASS") # never hardcode!

msg = MIMEMultipart("alternative")
msg["From"] = SENDER
msg["To"] = to_email
msg["Subject"] = subject
[Link](MIMEText(body_html, "html"))

with smtplib.SMTP_SSL("[Link]", 465) as server:


[Link](SENDER, PASSWORD)
[Link](SENDER, to_email, msg.as_string())
print(f"Report sent to {to_email}")

# Usage
# organise_folder("C:/Users/YourName/Downloads")
# send_report("manager@[Link]", "Weekly Sales Report",
"<h2>Report</h2>...")

Page 19 | MITS Academy | [Link]


MITS Academy — Python Programming Course

Module 8: Database Integration with SQLite


8.1 SQL and Python — Persistent Data Storage
Databases provide persistent, queryable, concurrent-safe data storage. SQLite is serverless (no
installation) — perfect for learning and small apps. Every serious application — web apps,
mobile apps, desktop tools — uses a database. Knowing SQL is one of the most in-demand
skills in the industry.
import sqlite3
from contextlib import contextmanager

# Context manager for clean connection handling


@contextmanager
def get_db(db_path):
conn = [Link](db_path)
conn.row_factory = [Link] # access columns by name
[Link]("PRAGMA foreign_keys = ON")
try:
yield conn
[Link]()
except Exception:
[Link]()
raise
finally:
[Link]()

# Setup
def init_db(db_path):
with get_db(db_path) as conn:
[Link]("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
course TEXT NOT NULL,
marks REAL DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS courses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
duration TEXT,
fee REAL
);
""")

# CRUD operations
def add_student(db, name, email, course, marks=0):
with get_db(db) as conn:
[Link](
"INSERT OR IGNORE INTO students(name,email,course,marks)
VALUES(?,?,?,?)",
(name, email, course, marks)
)

def get_top_students(db, n=5):


with get_db(db) as conn:
rows = [Link](

Page 20 | MITS Academy | [Link]


MITS Academy — Python Programming Course

"SELECT name,course,marks FROM students ORDER BY marks DESC


LIMIT ?",
(n,)
).fetchall()
return [dict(row) for row in rows]

def course_stats(db):
with get_db(db) as conn:
return [Link]("""
SELECT course,
COUNT(*) AS students,
AVG(marks) AS avg_marks,
MAX(marks) AS top_marks,
MIN(marks) AS low_marks
FROM students
GROUP BY course
ORDER BY avg_marks DESC
""").fetchall()

# Demo
init_db("[Link]")
for row in [
("Priya","priya@[Link]","Python",88),
("Arjun","arjun@[Link]","Java", 92),
("Meena","meena@[Link]","Python",79),
]:
add_student("[Link]", *row)

for s in get_top_students("[Link]"):
print(f"{s['name']} ({s['course']}): {s['marks']}")

Module 9: REST API Development with Flask


9.1 Building a Production-Ready REST API
REST APIs are the language of modern software. Mobile apps, web frontends, IoT devices, and
third-party integrations all communicate through APIs. Flask is a lightweight, flexible Python web
framework ideal for building APIs quickly. Understanding API design — endpoints, HTTP
methods, status codes, JSON — is essential for any backend developer.
# pip install flask flask-sqlalchemy
from flask import Flask, jsonify, request, abort
from functools import wraps

app = Flask(__name__)

# --- Middleware: simple API key auth ---


def require_api_key(f):
@wraps(f)
def decorated(*args, **kwargs):
key = [Link]("X-API-Key")
if key != "mits-secret-2024":
return jsonify({"error": "Unauthorised"}), 401
return f(*args, **kwargs)
return decorated

# --- In-memory store (replace with SQLAlchemy in production) ---


students = [
{"id":1,"name":"Priya Sharma","course":"Python","marks":88},

Page 21 | MITS Academy | [Link]


MITS Academy — Python Programming Course

{"id":2,"name":"Arjun Mehta", "course":"Java", "marks":92},


]
_next_id = 3

# --- Endpoints ---


@[Link]("/api/v1/students", methods=["GET"])
def get_students():
course = [Link]("course")
result = [s for s in students if not course or s["course"]==course]
return jsonify({"data": result, "total": len(result)})

@[Link]("/api/v1/students/<int:sid>", methods=["GET"])
def get_student(sid):
student = next((s for s in students if s["id"]==sid), None)
if not student:
abort(404)
return jsonify(student)

@[Link]("/api/v1/students", methods=["POST"])
@require_api_key
def create_student():
global _next_id
data = request.get_json(silent=True)
if not data:
return jsonify({"error": "JSON body required"}), 400

required = {"name", "course"}


missing = required - set([Link]())
if missing:
return jsonify({"error": f"Missing fields: {missing}"}), 422

student = {"id": _next_id, **{k: data[k] for k in ["name","course"]},


"marks": [Link]("marks", 0)}
[Link](student)
_next_id += 1
return jsonify(student), 201

@[Link]("/api/v1/students/<int:sid>", methods=["PUT"])
@require_api_key
def update_student(sid):
student = next((s for s in students if s["id"]==sid), None)
if not student:
abort(404)
data = request.get_json(silent=True) or {}
for k in ["name", "course", "marks"]:
if k in data:
student[k] = data[k]
return jsonify(student)

@[Link]("/api/v1/students/<int:sid>", methods=["DELETE"])
@require_api_key
def delete_student(sid):
global students
if not any(s["id"]==sid for s in students):
abort(404)
students = [s for s in students if s["id"] != sid]
return "", 204 # 204 No Content

# --- Error handlers ---


@[Link](404)
def not_found(e):

Page 22 | MITS Academy | [Link]


MITS Academy — Python Programming Course

return jsonify({"error": "Not found"}), 404

@[Link](405)
def method_not_allowed(e):
return jsonify({"error": "Method not allowed"}), 405

if __name__ == "__main__":
[Link](debug=True, port=5000)

# Test with curl:


# curl [Link]
# curl -X POST -H "X-API-Key: mits-secret-2024" \
# -H "Content-Type: application/json" \
# -d '{"name":"Meena","course":"ML","marks":91}' \
# [Link]

Practice Tasks and Capstone Projects


Module-wise Practice Tasks
Module 1 — Python Basics:
• Write a program that takes a student name and marks in 5 subjects, then prints total,
percentage, grade (A/B/C/D/F), and pass/fail status.
• Build a contact book using a dictionary — add, search, update, delete contacts. Save to
and load from a JSON file.
• Find all prime numbers up to 1000 using the Sieve of Eratosthenes, then plot their
distribution with Matplotlib.
Module 2 — Control Flow and Functions:
• Build a number guessing game: computer picks a random number 1-100, user gets 7
attempts with Higher/Lower hints. Track and display statistics across multiple games.
• Write a function that validates Indian mobile numbers, PAN card format, and email
addresses using string methods (no regex).
• Implement a simple ATM menu: check balance, deposit, withdraw, change PIN — loop
until the user exits.
Module 3 — OOP:
• Build a Library Management System: Book, Member, and Library classes. Support issue,
return, and overdue fine calculation.
• Create an Employee payroll system with Employee, Manager (bonus), and Contractor
(hourly rate) classes using inheritance.
• Implement a Stack, Queue, and LinkedList using Python classes with all standard
operations.
Modules 4-9 — Advanced:
• Parse a large CSV log file, extract error rates by hour, and generate a Matplotlib
dashboard report saved as a PNG.
• Scrape job listings from a public practice site. Filter by keyword and location. Store in
SQLite. Add new listings daily without duplicates.
• Build a Flask REST API for a personal expense tracker with categories, monthly
summaries, and budget alerts.

Page 23 | MITS Academy | [Link]


MITS Academy — Python Programming Course

Capstone Project 1: Student Management System


Build a full command-line application for managing a coaching institute. Requirements: SQLite
database with Students, Courses, and Enrollments tables. Full CRUD for students and
enrollments. Auto-calculate grades, rank, and percentage per course. Export report cards as
formatted text files. Pandas-powered analytics: average marks trend, top students per course,
attendance heatmap. Matplotlib charts: grade distribution, course popularity, monthly
enrollment. OOP design: Student, Course, Enrollment, ReportGenerator classes. Exception
handling for all database operations and file I/O.

Capstone Project 2: E-Commerce Analytics Pipeline


Build a complete data pipeline: Scrape product data from [Link] across all 50
pages. Clean and store in SQLite using Pandas. Perform EDA: price distribution by category,
rating vs availability correlation, price percentiles. Build 6 Seaborn/Matplotlib visualisations:
heatmap, scatter with regression, bar charts, histogram, box plot. Wrap in a Flask web app:
homepage shows a live dashboard, /api/products returns filtered JSON, /report downloads a
CSV. Apply OOP: Scraper, DataCleaner, Analyser, APIServer classes.

Capstone Project 3: Personal Finance Tracker API


Build a production-ready REST API. Features: User registration with hashed passwords
(bcrypt). JWT-based authentication (PyJWT). Income and expense recording with categories
(Food, Transport, Bills, Entertainment, Savings). Monthly budget setting per category. Real-time
alerts when spending exceeds budget. Statistical endpoints: monthly totals, category
breakdown, savings rate, spending trend. SQLite with Users, Transactions, Budgets, Categories
tables. Proper RESTful design: versioned URLs, consistent JSON responses, appropriate HTTP
status codes, pagination. Comprehensive error handling and input validation. This project
demonstrates all Python skills and is immediately resume-worthy.

Page 24 | MITS Academy | [Link]

You might also like