Python: Zero to Professional — Complete Notes
Full Python syllabus — syntax to OOP, Matplotlib, ML & DSA overviews, MySQL/MongoDB, and a capstone. Every topic with a real-life example.
Python HOME — what this course covers
This Rishtaara Python course takes you from your first print() to databases, machine learning, and DSA overviews.
Python is one of the most popular languages for web backends, automation, data science, and AI. Its readable syntax makes it ideal for beginners and professionals.
Real-life example: Learning Python is like learning to cook with a simple recipe book. The steps are clear, and you can start with soup (scripts) before making a full dinner (web apps).
- Basics: syntax, types, loops, functions, files
- OOP, modules, Matplotlib, and library intros
- ML overview, DSA overview, MySQL & MongoDB with Python
Python Intro — why Python?
Python runs on Windows, Mac, and Linux. You write .py files and run them with the python command or inside tools like VS Code.
Companies use Python for Django websites, data pipelines, testing tools, and machine learning models.
Real-life example: Python is like a Swiss Army knife — one tool that opens bottles (scripts), cuts rope (data tasks), and tightens screws (web APIs).
Python Get Started — install and first run
Download Python from python.org (3.10+ recommended). Check your version with python --version in the terminal.
Create a file hello.py, write print("Hello, World!"), and run python hello.py.
Real-life example: Installing Python is like getting keys to a workshop. hello.py is your first small project on the workbench.
# hello.py
print("Hello, Rishtaara!")
print("Welcome to Python Zero to Pro.")Python Syntax
Python uses indentation (spaces) to define blocks — not curly braces. A colon (:) starts a block after if, for, def, and class.
Python is case-sensitive: name and Name are different variables.
Real-life example: Indentation is like margins in a notebook — wrong margins make the teacher think your answer belongs to the wrong question.
score = 85
if score >= 60:
print("Pass") # indented block
print("Done")Python Output
print() sends text to the screen. You can print variables, expressions, and multiple items separated by commas.
f-strings (f"...") embed values inside strings cleanly.
Real-life example: print() is like speaking out loud in class — everyone sees the result immediately on the screen.
name = "Aarav"
print("Hello", name)
print(f"Hello {name}, welcome to Rishtaara!")Python Comments
Comments start with # for one line. Triple quotes """ ... """ can document functions and classes.
Comments explain why — not what obvious code already shows.
Real-life example: Comments are sticky notes on your fridge — reminders for you, ignored by guests (the computer).
# This line is a comment
price = 100 # discount base price
def add_tax(amount):
"""Add 18% tax and return total."""
return amount * 1.18Python Variables
Variables store values. You assign with = — no type keyword needed.
Use snake_case names like user_name. Start with a letter, not a number.
Real-life example: A variable is a labeled box in storage — the label stays, but you can swap what is inside.
course = "Python Zero to Pro"
lesson = 3
print(course, lesson)Python Data Types
Common types: str (text), int (whole numbers), float (decimals), bool (True/False), list, tuple, set, dict.
Use type() to inspect a value's type at runtime.
Real-life example: Data types are like container shapes — you would not pour soup into a letter envelope (str vs list).
name = "Meera" # str
age = 21 # int
gpa = 3.8 # float
active = True # bool
print(type(name), type(age))Python Numbers
int handles whole numbers; float handles decimals. Python supports +, -, *, /, //, %, and **.
Division / always returns float. // is floor division.
Real-life example: int is counting whole apples; float is weighing flour on a kitchen scale.
a, b = 10, 3
print(a + b, a / b, a // b, a % b, a ** b)Python Casting
Casting converts one type to another: int(), float(), str(), bool().
Wrap risky conversions in try/except when reading user input.
Real-life example: Casting is like converting rupees to dollars — same value, different format for the receiver.
text = "42"
number = int(text)
print(number + 8)
value = str(99)
print("Score: " + value)Python Strings
Strings are text in single or double quotes. They support slicing, len(), upper(), lower(), strip(), and in.
Strings are immutable — methods return new strings.
Real-life example: A string is a necklace of letter beads — you can read a section (slice) but each bead stays in order.
msg = " Hello Python "
print(msg.strip().upper())
print(msg[2:7]) # HelloPython Booleans
bool values are True and False (capital T and F). Comparisons and logic operators produce booleans.
Empty strings, 0, None, and empty collections are falsy in if checks.
Real-life example: A boolean is a traffic light — only green (True) or red (False), no maybe.
logged_in = True
print(logged_in and True)
print(not logged_in)
print(bool(""), bool("hi"), bool(0))Python Operators
Arithmetic: + - * / // % **. Comparison: == != > < >= <=. Logical: and or not. Assignment: += -= etc.
Membership: in / not in. Identity: is / is not (compare object identity).
Real-life example: Operators are kitchen tools — + adds ingredients, == checks if two bowls hold the same amount.
x, y = 10, 4
print(x > y, x == y)
print("py" in "python")
count = 5
count += 1
print(count)Python Lists
Lists are ordered, mutable collections in square brackets []. Methods: append, extend, insert, remove, pop, sort.
Lists can hold mixed types and are the default dynamic array in Python.
Real-life example: A list is a shopping list — you can add, remove, and reorder items anytime.
skills = ["python", "sql"]
skills.append("git")
skills[0] = "Python"
print(skills, len(skills))Python Tuples
Tuples use parentheses () and are ordered but immutable — good for fixed records like coordinates.
Unpacking lets you assign multiple variables at once.
Real-life example: A tuple is a sealed exam paper — you can read it but not erase answers.
point = (10, 20)
x, y = point
print(x, y)Python Sets
Sets store unique unordered items in curly braces {}. Great for removing duplicates and membership tests.
Set operations include union (|), intersection (&), and difference (-).
Real-life example: A set is a bag of unique marbles — duplicate colors automatically disappear.
tags = {"api", "backend", "api"}
print(tags) # {'api', 'backend'}Python Dictionaries
Dicts map keys to values with {}. Keys must be hashable (usually strings or numbers).
Use .get() for safe access, .keys(), .values(), .items() for loops.
Real-life example: A dictionary is a phone contact book — name (key) points to number (value).
student = {"name": "Riya", "score": 92}
student["score"] = 95
print(student.get("name"), student["score"])Python If...Else
if, elif, and else choose code paths based on conditions. Always indent the block after the colon.
Combine conditions with and, or, and not.
Real-life example: If/else is a gatekeeper — if you have a ticket, you enter; else you wait outside.
marks = 86
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
else:
grade = "C"
print(grade)Python Match
match/case (Python 3.10+) compares a value against patterns — cleaner than long elif chains.
Use _ as the default case wildcard.
Real-life example: match is a vending machine menu — press A for chips, B for soda, default for cancel.
status = "success"
match status:
case "success":
print("Done!")
case "error":
print("Failed.")
case _:
print("Unknown.")Python While Loops
while repeats a block while a condition is True. Watch for infinite loops — update the condition inside.
break exits the loop; continue skips to the next iteration.
Real-life example: while is like stirring soup until it boils — keep going until the condition changes.
count = 3
while count > 0:
print(count)
count -= 1
print("Go!")Python For Loops
for item in iterable loops over lists, strings, dicts, and more. Prefer for when you know what you are iterating.
Use enumerate() when you need both index and value.
Real-life example: for is like checking each student in a roll call — one name at a time until the list ends.
topics = ["syntax", "loops", "functions"]
for i, topic in enumerate(topics, start=1):
print(i, topic.title())Python Range
range(stop), range(start, stop), range(start, stop, step) generate number sequences without storing a full list.
Common pattern: for i in range(5):
Real-life example: range is a numbered ticket dispenser — it hands you 0, 1, 2… without printing all tickets at once.
print(list(range(5)))
print(list(range(2, 10, 2)))Python Functions
Define functions with def name():. Use parameters, default values, and return to send results back.
Keep functions small and focused on one job.
Real-life example: A function is a coffee machine button — press once, same steps run every time.
def greet(name, role="student"):
return f"Hello {name}, you are a {role}."
print(greet("Meera"))
print(greet("Carlos", "instructor"))Python User Input
input() reads text from the keyboard. Always returns a string — cast to int/float when needed.
Validate input and handle errors with try/except for robust CLI apps.
Real-life example: input() is a waiter asking your order — you speak, Python writes it down as text.
raw = input("Enter your age: ")
try:
age = int(raw)
print(f"Next year you will be {age + 1}.")
except ValueError:
print("Please enter a valid number.")Python Arrays — note
Python lists are the usual dynamic array. For strict numeric arrays, use the array module or NumPy (covered later).
Note: lists handle most everyday array needs in Python.
Real-life example: A Python list is a flexible shelf — hold books, boxes, or both. NumPy is a specialized warehouse for numbers.
# Most code uses lists
nums = [1, 2, 3, 4]
# Strict typed array (optional)
import array
typed = array.array("i", [1, 2, 3])
print(nums, list(typed))Python Iterators
Iterators produce values one at a time. iter() and next() walk through objects manually.
for loops use iterators under the hood. Classes can define __iter__ and __next__.
Real-life example: An iterator is a PEZ dispenser — one candy at a time until empty.
values = iter(["a", "b", "c"])
print(next(values))
print(next(values))Python Modules
Modules are .py files with reusable code. import math, from datetime import date, or import my_helpers.
Split large programs into modules for clarity and testing.
Real-life example: Modules are chapters in a cookbook — import dessert when you need cake, not the whole book at once.
import math
from datetime import date
print(math.sqrt(16))
print(date.today())Python Dates
The datetime module handles dates and times. datetime.now(), strftime(), and timedelta for differences.
Store dates as ISO strings in JSON; parse with fromisoformat() when needed.
Real-life example: datetime is a calendar plus clock on your phone — one module for today and tomorrow.
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d"))
print(now + timedelta(days=7))Python Math
Built-in math module: sqrt, pow, ceil, floor, pi, sin, cos. For heavy stats use statistics (later).
Use ** or math.pow for powers; // and % for integer division and remainder.
Real-life example: math is a calculator drawer — square roots and trig without reinventing formulas.
import math
print(math.sqrt(25), math.pi)
print(math.ceil(4.2), math.floor(4.8))Python JSON
json.dumps() converts Python dict/list to JSON string. json.loads() parses JSON back.
json.dump() and json.load() read/write JSON files — common for configs and APIs.
Real-life example: JSON is a universal packing box — Python dicts ship safely to JavaScript apps inside.
import json
data = {"course": "python-zero-to-pro", "lesson": 10}
text = json.dumps(data)
parsed = json.loads(text)
print(parsed["course"])Python RegEx
The re module matches patterns in text. re.search(), re.findall(), re.sub() are common.
Raw strings r"pattern" avoid backslash escaping headaches.
Real-life example: RegEx is a custom search filter — find all emails in a paragraph, not just one word.
import re
text = "Contact: support@knowvora.com"
match = re.search(r"[\w.-]+@[\w.-]+", text)
print(match.group() if match else "No email")Python PIP
pip installs third-party packages: pip install requests, pip list, pip show package.
Use python -m pip install package for reliability. Pin versions in requirements.txt for projects.
Real-life example: pip is an app store for Python — one command downloads tools others built.
# Run in terminal — not inside .py file
# python -m pip install requests
# python -m pip list
# python -m pip freeze > requirements.txtPython Try...Except
try/except catches errors so programs do not crash. Use specific exceptions like ValueError, FileNotFoundError.
else runs if no error; finally always runs (cleanup).
Real-life example: try/except is a safety net under a trapeze — the show continues even if one move fails.
try:
score = int("abc")
except ValueError:
print("Invalid number")
finally:
print("Attempt finished")Python String Formatting
f-strings are the modern default: f"{name} scored {score}". .format() and % formatting still appear in older code.
Format numbers: f"{price:.2f}", f"{n:,}" for thousands separators.
Real-life example: String formatting is filling a form letter — same sentence, different names each time.
name, score = "Riya", 92.567
print(f"{name} scored {score:.1f}%")
print("{} scored {:.1f}%".format(name, score))Python None
None means no value or missing data. Functions without return implicitly return None.
Check with is None — not == None. Optional parameters often default to None.
Real-life example: None is an empty chair — the seat exists but nobody is sitting there yet.
result = None
def find_user(id):
return None # not found
user = find_user(99)
if user is None:
print("User not found")Python VirtualEnv
Virtual environments isolate project packages. Create with python -m venv venv, activate, then pip install.
On Mac/Linux: source venv/bin/activate. On Windows: venv\Scripts\activate.
Real-life example: VirtualEnv is a separate kitchen for each recipe — spices from one dish do not mix into another.
# Terminal steps
# python -m venv venv
# source venv/bin/activate # Mac/Linux
# pip install requests
# deactivateBasics checkpoint — you covered
You now know syntax, types, collections, control flow, functions, modules, JSON, RegEx, errors, and environment setup.
Next: OOP, files, data libraries, Matplotlib, ML overview, DSA, and databases.
Real-life example: Basics are learning to walk — OOP and databases are learning to run marathons with proper shoes.
- Every core Python topic through VirtualEnv
- Practice on /mcq/python-mcq after each part
- Re-read sections with code and run examples locally
Python Exercises — practice habits
After each lesson, rewrite examples without looking. Change values and predict output before running.
Use the practice drills per chapter to confirm you understand lists, loops, and functions.
Real-life example: Practice is gym reps — reading teaches the move; typing code builds muscle memory.
Mini challenge — combine basics
Build a small grade tracker: read names and scores, store in a dict, print average and highest grade.
Use if/else, loops, functions, try/except, and f-strings together.
Real-life example: A class teacher's register — add students, fix mistakes, print summary at end of day.
def average(scores):
return sum(scores) / len(scores) if scores else 0
grades = {"Aarav": 88, "Meera": 94, "Riya": 91}
print("Average:", average(list(grades.values())))
print("Top:", max(grades, key=grades.get))Python OOP
Object-Oriented Programming models real things as objects with data (attributes) and behavior (methods).
OOP helps organize large codebases — each class owns its logic.
Real-life example: OOP is a school — Student and Teacher are different roles with different duties but same campus rules.
Python Classes/Objects
A class is a blueprint; an object is one instance built from it. Create objects by calling ClassName().
Attributes store state; methods define actions on that state.
Real-life example: Cookie cutter (class) vs one actual cookie (object) — same shape, each can have different icing.
class Dog:
species = "Canis"
def bark(self):
return "Woof!"
my_dog = Dog()
print(my_dog.bark())Python __init__ Method
__init__ runs when a new object is created. It sets starting values for attributes.
It is the constructor — not named 'constructor' in Python but serves the same role.
Real-life example: __init__ is filling a new employee form on day one — name, ID, and desk assigned immediately.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
acct = BankAccount("Ananya", 1000)
print(acct.owner, acct.balance)Python self Parameter
self is the first parameter of instance methods — it refers to the current object.
Python passes the object automatically when you call account.deposit(50).
Real-life example: self is saying 'my own wallet' — each person reaches into their pocket, not someone else's.
class Counter:
def __init__(self):
self.count = 0
def add(self, n=1):
self.count += n
return self.count
c = Counter()
print(c.add(), c.add(5))Python Class Properties
Properties are attributes on objects — set in __init__ or assigned later.
Use @property for computed or validated fields (e.g. read-only balance).
Real-life example: Properties are labels on storage boxes — owner, balance, status — visible without opening everything.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return 3.14 * self.radius ** 2
c = Circle(5)
print(c.area)Python Class Methods
Instance methods use self. @classmethod receives cls — good for alternate constructors.
@staticmethod needs no self or cls — utility tied to the class namespace.
Real-life example: Instance method is one student raising a hand; classmethod is the whole class taking attendance.
class User:
def __init__(self, name):
self.name = name
@classmethod
def guest(cls):
return cls("Guest")
@staticmethod
def validate(name):
return len(name) >= 2
print(User.guest().name)
print(User.validate("Al"))Python Inheritance
A child class extends a parent: class Dog(Animal). It inherits attributes and methods.
Override methods in the child for specialized behavior. super() calls the parent version.
Real-life example: Inheritance is a family recipe — you keep the base dish and add your own spice.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
print(Dog().speak())Python Polymorphism
Polymorphism means different classes can respond to the same method name differently.
Duck typing: if it quacks like a duck, use it — Python cares about behavior, not exact type.
Real-life example: A 'Play' button on TV, phone, and speaker — same action, different devices inside.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
for animal in [Cat(), Dog()]:
print(animal.speak())Python Encapsulation
Encapsulation hides internal details. Convention: prefix with _ for 'private' (still accessible but a hint).
Use methods to validate changes instead of editing attributes from everywhere.
Real-life example: Encapsulation is an ATM — you press buttons, not open the vault yourself.
class Account:
def __init__(self):
self._balance = 0
def deposit(self, amount):
if amount > 0:
self._balance += amount
def get_balance(self):
return self._balancePython Inner Classes
A class defined inside another class can group related helpers tightly.
Use when the inner class only makes sense with the outer one — not for every project.
Real-life example: Inner class is a drawer inside one desk — not a separate room in the building.
class University:
class Student:
def __init__(self, name):
self.name = name
def enroll(self, name):
return self.Student(name)
u = University()
s = u.enroll("Riya")
print(s.name)Python File Handling
Files store data on disk — logs, configs, CSV exports. Always close files or use with open(...).
Modes: 'r' read, 'w' write (overwrite), 'a' append, 'x' create if missing.
Real-life example: File handling is a notebook — read pages, write new notes, tear out old ones (delete).
Python Read Files
read() loads entire file; readline() one line; readlines() list of lines.
Loop directly over the file object for memory-efficient reading of large files.
Real-life example: Reading a file line by line is reading a novel page by page instead of memorizing the whole book.
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())Python Write/Create Files
Mode 'w' creates or overwrites. 'a' adds to the end without erasing.
Specify encoding='utf-8' for international text.
Real-life example: Writing a file is printing a new receipt — 'w' replaces the old receipt, 'a' adds another line.
with open("log.txt", "w", encoding="utf-8") as f:
f.write("Session started\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("User logged in\n")Python Delete Files
Use os.remove(path) to delete a file. os.path.exists() checks first.
For folders use shutil.rmtree — be careful, deletion is permanent.
Real-life example: Deleting a file is throwing a paper in the shredder — confirm before you do it.
import os
path = "temp.txt"
if os.path.exists(path):
os.remove(path)
print("Deleted")NumPy — intro
NumPy provides fast numeric arrays (ndarray) and math operations on whole arrays at once.
Install: pip install numpy. Foundation for Pandas, SciPy, and ML libraries.
Real-life example: NumPy is a spreadsheet engine — multiply entire columns in one step, not cell by cell.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2)
print(arr.mean())Pandas — intro
Pandas adds DataFrame tables — like Excel in Python. read_csv(), head(), describe() explore data.
Essential for data cleaning, analysis, and ML preprocessing.
Real-life example: Pandas is a smart ledger — rows are records, columns are fields, filters are one line.
import pandas as pd
data = {"name": ["A", "B"], "score": [88, 92]}
df = pd.DataFrame(data)
print(df)
print(df["score"].mean())SciPy — intro
SciPy builds on NumPy with scientific algorithms — optimization, statistics, signal processing.
Use scipy.stats for distributions and scipy.optimize for finding minima.
Real-life example: SciPy is the lab equipment room — advanced instruments built on NumPy's workbench.
from scipy import stats
sample = [2, 4, 4, 4, 5, 5, 7, 9]
print(stats.mode(sample, keepdims=True))Django — intro
Django is a full Python web framework — URLs, views, templates, ORM, admin panel.
Install: pip install django. django-admin startproject mysite starts a new site.
Real-life example: Django is a prefab house kit — walls, plumbing, and wiring included for web apps.
# views.py (concept)
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello from Django!")Matplotlib Intro
Matplotlib draws charts in Python — line, bar, scatter, histogram, pie. Install: pip install matplotlib.
It is the standard plotting library paired with NumPy and Pandas.
Real-life example: Matplotlib is graph paper that draws itself — you give numbers, it sketches the picture.
Matplotlib Pyplot
Import as import matplotlib.pyplot as plt. plt.plot(), plt.show() display charts.
Works in scripts and Jupyter notebooks.
Real-life example: pyplot is the remote for your chart TV — plot, label, then show.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 1, 5]
plt.plot(x, y)
plt.show()Matplotlib Plotting & Markers
Customize lines with color, linestyle, linewidth. Markers: 'o', 's', '^' show points.
plt.plot(x, y, marker='o', color='green', linestyle='--')
Real-life example: Markers are pins on a map — the line is the road, pins show stops.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [3, 2, 5], marker="o", color="blue")
plt.show()Matplotlib Line
Multiple plt.plot() calls overlay lines. Use legend() to label each series.
Line charts show trends over time — sales, temperature, scores.
Real-life example: Multiple lines on one chart compare two students' progress on the same exam timeline.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9], label="A")
plt.plot([1, 2, 3], [2, 3, 8], label="B")
plt.legend()
plt.show()Matplotlib Labels & Titles
plt.title(), plt.xlabel(), plt.ylabel() describe the chart for readers.
Always label axes in reports — unexplained charts confuse teammates.
Real-life example: Labels are signboards on a highway — without them, drivers guess the destination.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [10, 20, 15])
plt.title("Weekly Scores")
plt.xlabel("Week")
plt.ylabel("Points")
plt.show()Matplotlib Grid
plt.grid(True) adds background lines for easier reading of values.
Use alpha=0.3 for subtle grids that do not overpower the data.
Real-life example: Grid lines are notebook margins — they help you align numbers without doing math in your head.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [5, 7, 4])
plt.grid(True, alpha=0.3)
plt.show()Matplotlib Subplot
plt.subplot(rows, cols, index) or plt.subplots() show multiple charts in one figure.
Compare related views side by side — price vs volume, train vs test accuracy.
Real-life example: Subplots are a comic strip — four panels, one story, different angles.
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 2], [3, 4])
ax2.bar(["A", "B"], [5, 8])
plt.show()Matplotlib Scatter
plt.scatter(x, y) shows individual points — ideal for correlations and clusters.
Add plt.scatter(x, y, c=colors, s=sizes) for color and size encoding.
Real-life example: Scatter plots are stars in the sky — each point is one observation, patterns form constellations.
import matplotlib.pyplot as plt
hours = [1, 2, 3, 4, 5]
scores = [55, 60, 72, 78, 90]
plt.scatter(hours, scores)
plt.xlabel("Study hours")
plt.ylabel("Score")
plt.show()Matplotlib Bars
plt.bar(categories, values) compares discrete groups — sales by region, votes by party.
plt.barh() is horizontal bars when labels are long.
Real-life example: Bar charts are city skylines — taller buildings mean bigger values.
import matplotlib.pyplot as plt
courses = ["Python", "JS", "SQL"]
students = [120, 95, 80]
plt.bar(courses, students)
plt.show()Matplotlib Histograms
plt.hist(data, bins=10) shows frequency distribution — ages, exam scores, response times.
Choose bin count to balance detail vs noise.
Real-life example: A histogram is sorting mail into slots — see which score ranges pile up highest.
import matplotlib.pyplot as plt
scores = [62, 71, 75, 80, 82, 88, 91, 95]
plt.hist(scores, bins=5)
plt.xlabel("Score")
plt.ylabel("Count")
plt.show()Matplotlib Pie Charts
plt.pie(sizes, labels=labels, autopct='%1.1f%%') shows parts of a whole.
Best for few categories — too many slices become unreadable.
Real-life example: Pie charts are pizza slices — each slice shows who ate what share.
import matplotlib.pyplot as plt
labels = ["Python", "JS", "Other"]
sizes = [45, 35, 20]
plt.pie(sizes, labels=labels, autopct="%1.0f%%")
plt.show()Random module
random.randint, random.choice, random.shuffle, random.random for simulations and games.
Use secrets module for security (passwords, tokens) — not random.
Real-life example: random.choice is a lucky draw bowl — pick one winner from a list of names.
import random
print(random.randint(1, 6))
print(random.choice(["apple", "banana", "mango"]))Requests module
requests.get(url) fetches web pages and APIs. Check response.status_code and response.json().
Install: pip install requests. Always handle timeouts and errors.
Real-life example: requests is a postal worker — you give an address (URL), it brings back the reply.
import requests
resp = requests.get("https://api.github.com", timeout=5)
print(resp.status_code)
print(resp.headers.get("Content-Type"))Statistics module
statistics.mean, median, mode, stdev work on Python lists — no NumPy required.
Good for quick summaries in scripts and homework.
Real-life example: statistics.mean is the class average — one number summarizing everyone's test.
import statistics
scores = [80, 85, 90, 92, 88]
print(statistics.mean(scores))
print(statistics.median(scores))Math module (reference highlights)
math.sqrt, pow, ceil, floor, factorial, gcd, sin, cos, log, pi, e.
For vector math use NumPy; math is for scalar operations.
Real-life example: math.factorial is counting arrangements — how many ways to order 5 books on a shelf.
import math
print(math.sqrt(49), math.factorial(5))
print(math.gcd(48, 18))
print(round(math.sin(math.pi / 2), 2))Remove List Duplicates
Convert to set and back: list(dict.fromkeys(items)) preserves order in Python 3.7+.
Or loop and append only if not seen — full control over which duplicate to keep.
Real-life example: Removing duplicates is deduplicating a guest list — each person invited once.
items = [1, 2, 2, 3, 1, 4]
unique = list(dict.fromkeys(items))
print(unique) # [1, 2, 3, 4]Reverse a String
Slicing [::-1] reverses any sequence — strings, lists, tuples.
Or use reversed() and join for strings: ''.join(reversed(text)).
Real-life example: Reversing a string is reading a sign in a mirror — last letter becomes first.
text = "Python"
print(text[::-1])
print("".join(reversed(text)))Add Two Numbers
Simple: a + b. For user input, cast with int() inside try/except.
This is a classic first logic exercise — foundation for calculators.
Real-life example: Adding two numbers is a cashier totaling two items — basic but everywhere.
a = int(input("First number: "))
b = int(input("Second number: "))
print("Sum:", a + b)Python Exercises
These exercises test one chapter at a time — lists, loops, OOP, file I/O.
On Rishtaara, use /mcq/python-mcq after each part. Rewrite examples from memory.
Real-life example: Exercises are driving practice in an empty parking lot before highway traffic.
- Redo wrong answers the next day
- Mix topics: read a JSON file, plot results with Matplotlib
- Time yourself — 15-minute mini drills
Python Examples library
Earlier lesson examples show copy-paste snippets for every topic — great when you forget syntax.
Build a personal snippets folder: strings.py, files.py, plots.py.
Real-life example: Examples are recipe cards — follow once, then cook from memory.
Python Quiz
Our Python MCQs check syntax, types, and common mistakes across the full tutorial.
Take it after lessons 1–25. Aim for 80%+ before moving to ML and database sections.
Real-life example: A quiz is a mock exam — lower stakes, shows gaps before the real test.
Python Challenges
Coding challenges add constraints — reverse words, count vowels, parse CSV rows.
Combine OOP + files + modules for medium challenges.
Real-life example: Challenges are puzzle levels in a game — same tools, harder layout.
def count_vowels(text):
return sum(1 for ch in text.lower() if ch in "aeiou")
print(count_vowels("Rishtaara"))Python Certification
After this course, practice with our Python MCQs covering basics through OOP, files, and modules.
Rishtaara's python-zero-to-pro path prepares you — finish all 40 lessons, MCQs, and interview sets.
Real-life example: Certification is a driving license — practice hours matter more than the card alone.
Python Reference — quick map
Bookmark built-in functions, str/list/dict methods, keywords, and exceptions in the official Python docs.
In daily work, IDE autocomplete plus official docs beat memorizing every method.
Real-life example: Reference pages are a dictionary — you look up words, not memorize the whole book.
- Built-in Functions — len, range, print, type
- String/List/Dict Methods — append, split, keys
- Keywords — def, class, import, return
- Exceptions — ValueError, KeyError, FileNotFoundError
Machine Learning — Getting Started
Machine Learning (ML) teaches computers to learn patterns from data instead of hard-coded rules.
Python is the top ML language thanks to NumPy, Pandas, scikit-learn, and Matplotlib.
Real-life example: ML is a student who improves by practicing past exam papers — not memorizing one answer key.
Data Set
A data set is any collection — a Python list, CSV file, or database table.
ML starts by exploring raw data before building models.
Real-life example: A data set is a cricket scorebook — rows are matches, columns are runs, wickets, overs.
scores = [88, 92, 75, 81, 95]
print(len(scores), max(scores), min(scores))Data Types — Numerical, Categorical, Ordinal
Numerical: discrete (counts) or continuous (measurements). Categorical: labels like colors. Ordinal: ordered categories like grades.
Knowing types tells you which algorithms and preprocessing steps fit.
Real-life example: Shoe size (numerical) vs brand (categorical) vs rating stars (ordinal) — different questions need different tools.
Viewing Data with Python
Pandas read_csv() and head() preview tables. Look before you model.
Spot missing values, wrong types, and outliers early.
Real-life example: Viewing data is opening the hood before driving — see if anything is leaking.
import pandas as pd
data = {"name": ["A", "B", "C"], "score": [88, 92, 75]}
df = pd.DataFrame(data)
print(df.head())
print(df.info())Data Dimensions
df.shape returns (rows, columns). Large row counts mean more training examples.
Too many columns without enough rows can cause overfitting.
Real-life example: Dimensions are classroom size — 30 students × 5 subjects is a clear grid to reason about.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]})
print(df.shape) # (2, 3)Statistics with Python
Statistics summarize data — central tendency, spread, and distribution shape.
Pandas describe() shows count, mean, std, min, quartiles, max in one table.
Real-life example: Statistics are a weather report summary — not every hourly reading, but today's high, low, and average.
import pandas as pd
df = pd.DataFrame({"score": [80, 85, 90, 92, 88]})
print(df.describe())Mean, Median, Mode
Mean is average; median is middle value; mode is most frequent.
Use median when outliers skew the mean (e.g. one very high salary).
Real-life example: Mean house price in a street with one mansion misleads — median tells a fairer story.
import statistics
data = [2, 3, 3, 5, 7]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.mode(data))Standard Deviation
Standard deviation measures spread around the mean. Low std = values clustered; high std = scattered.
Many ML models assume features are on similar scales — std helps you check that.
Real-life example: Std dev is how spread out arrival times are — buses on time vs randomly late.
import statistics
tight = [10, 11, 10, 9, 10]
wide = [1, 15, 8, 20, 3]
print(statistics.stdev(tight), statistics.stdev(wide))Percentile
The 25th percentile (Q1) means 25% of values fall below it. Median is the 50th percentile.
Percentiles rank students, response times, and income bands.
Real-life example: Top 10% exam score means your mark is above the 90th percentile.
import numpy as np
scores = [55, 60, 72, 78, 90, 95]
print(np.percentile(scores, 25))
print(np.percentile(scores, 90))Class Distribution
For classification, check how many examples per class. Imbalanced sets need special care.
value_counts() or groupby().size() in Pandas reveals balance.
Real-life example: Class distribution is counting yes vs no votes — a 99–1 split needs different handling than 50–50.
import pandas as pd
df = pd.DataFrame({"label": ["spam", "ham", "ham", "ham", "spam"]})
print(df["label"].value_counts())Correlation and Skew with Python
Correlation (Pearson) shows how two numeric columns move together — from -1 to +1.
df.corr() builds a correlation matrix for all numeric columns.
Real-life example: Ice cream sales and temperature correlate — both rise in summer, not because one eats the other.
import pandas as pd
df = pd.DataFrame({"hours": [1, 2, 3, 4], "score": [55, 65, 75, 85]})
print(df.corr())Skew Distributions
Skew measures asymmetry. Positive skew has a long right tail.
df.skew() on numeric columns guides preprocessing choices.
Real-life example: Income data is often right-skewed — a few very high earners pull the tail right.
import pandas as pd
df = pd.DataFrame({"values": [1, 2, 2, 3, 100]})
print(df.skew())Data Preprocessing
Preprocessing cleans and transforms raw data before modeling — handle missing values, encode categories, scale numbers.
Good preprocessing often beats fancy algorithms on messy data.
Real-life example: Preprocessing is washing vegetables before cooking — same recipe fails on dirty inputs.
Data Rescale
MinMaxScaler maps features to a range (often 0–1). Helps algorithms sensitive to magnitude.
Real-life example: Rescaling is converting all measurements to the same unit before comparing height and weight charts.
from sklearn.preprocessing import MinMaxScaler
X = [[10], [20], [30]]
scaler = MinMaxScaler()
print(scaler.fit_transform(X))Normalize Data with Python
Normalizer scales each row to unit length (L2 norm). Common for text features and some distance models.
Real-life example: Normalizing is adjusting each student's mix of subjects to compare fairly when totals differ.
from sklearn.preprocessing import Normalizer
X = [[1, 2, 3], [4, 5, 6]]
print(Normalizer().fit_transform(X))Standardized Data with Python
StandardScaler sets mean 0 and std 1 — z-score normalization. Works well when data is roughly Gaussian.
Real-life example: Standardizing is grading on a curve — everyone's score relative to class average.
from sklearn.preprocessing import StandardScaler
X = [[0], [10], [20]]
print(StandardScaler().fit_transform(X))Binarized Data with Python
Binarizer converts values above a threshold to 1, else 0. Used in image masks and simple flags.
Real-life example: Binarizing is a pass/fail stamp — scores above 40 become pass (1), else fail (0).
from sklearn.preprocessing import Binarizer
X = [[0.5], [1.2], [2.8]]
print(Binarizer(threshold=1.0).transform(X))Data Distribution
Distribution describes how values spread — uniform, skewed, or bell-shaped.
Histograms and KDE plots visualize distributions before choosing models.
Real-life example: Data distribution is the shape of crowds at a mall — quiet morning vs packed evening.
Normal Data Distribution
Many natural phenomena follow a bell curve (Gaussian). Mean ≈ median when symmetric.
Linear models and some stats assume near-normal residuals.
Real-life example: Heights of adults cluster around average with fewer very short or very tall — classic bell curve.
import matplotlib.pyplot as plt
data = [68, 70, 72, 71, 69, 73, 71, 70]
plt.hist(data, bins=5)
plt.title("Score distribution")
plt.show()Scatter Plot
Scatter plots show relationship between two numeric variables — linear, curved, or none.
First step before regression: eyes on the chart.
Real-life example: Scatter plot of study hours vs marks — dots climbing right mean more study helps.
import matplotlib.pyplot as plt
hours = [1, 2, 3, 4, 5]
scores = [55, 62, 70, 78, 88]
plt.scatter(hours, scores)
plt.xlabel("Hours")
plt.ylabel("Score")
plt.show()Scale
Features on different scales (age 0–100 vs income 0–1M) can bias distance-based models.
Always scale before KNN, SVM, neural nets, and many clustering methods.
Real-life example: Scale is using the same ruler — comparing cm to miles without conversion misleads.
Train/Test
Split data: train on one part, test on unseen rows to measure real performance.
train_test_split from sklearn is the standard pattern.
Real-life example: Train/test is studying with practice papers then taking a new exam — not the same questions.
from sklearn.model_selection import train_test_split
X = [[1], [2], [3], [4], [5]]
y = [2, 4, 6, 8, 10]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(len(X_train), len(X_test))Linear Regression
Linear regression fits a straight line predicting a numeric target from features.
Use when relationship looks roughly linear on a scatter plot.
Real-life example: Predicting electricity bill from units used — more units, higher bill, roughly straight line.
from sklearn.linear_model import LinearRegression
X = [[1], [2], [3], [4]]
y = [2, 4, 5, 4]
model = LinearRegression().fit(X, y)
print(model.predict([[5]]))Polynomial Regression
Polynomial features let the line curve — good when growth accelerates or slows.
Risk overfitting if degree is too high for small data.
Real-life example: Plant height vs weeks — slow start, fast middle, plateau — not a straight line.
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
X = np.array([[1], [2], [3], [4]])
y = [1, 4, 9, 16]
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
model = LinearRegression().fit(X_poly, y)
print(model.score(X_poly, y))Multiple Regression
Multiple features predict one target — e.g. hours studied + attendance → exam score.
Same LinearRegression with multi-column X.
Real-life example: House price from size, bedrooms, and location — many inputs, one price output.
from sklearn.linear_model import LinearRegression
X = [[1, 80], [2, 85], [3, 90]]
y = [55, 65, 75]
model = LinearRegression().fit(X, y)
print(model.predict([[4, 88]]))Logistic Regression
Logistic regression predicts classes (yes/no) using a sigmoid curve — despite the name, it classifies.
Outputs probabilities you can threshold at 0.5.
Real-life example: Email spam filter — words and sender stats predict spam (1) or ham (0).
from sklearn.linear_model import LogisticRegression
X = [[0.5], [1.0], [1.5], [2.0]]
y = [0, 0, 1, 1]
model = LogisticRegression().fit(X, y)
print(model.predict([[1.2]]))Decision Tree
Decision trees split data with if/else rules — easy to visualize and explain.
Can overfit deep trees; limit max_depth for generalization.
Real-life example: Loan approval — if income > X and credit > Y then approve, else reject.
from sklearn.tree import DecisionTreeClassifier
X = [[1], [2], [3], [4]]
y = [0, 0, 1, 1]
model = DecisionTreeClassifier(max_depth=2).fit(X, y)
print(model.predict([[2.5]]))Confusion Matrix
Confusion matrix counts true/false positives and negatives — better than accuracy alone on imbalanced data.
confusion_matrix and classification_report in sklearn summarize results.
Real-life example: Medical test — false negative misses disease; false positive causes extra stress.
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.tree import DecisionTreeClassifier
X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 1]
model = DecisionTreeClassifier().fit(X, y)
pred = model.predict(X)
print(confusion_matrix(y, pred))
print(classification_report(y, pred))Hierarchical Clustering
Hierarchical clustering builds a tree of clusters — agglomerative (bottom-up) is common.
Useful when you do not know K in advance and want a dendrogram view.
Real-life example: Organizing family photos into nested folders — siblings, then cousins, then whole family.
from sklearn.cluster import AgglomerativeClustering
X = [[1], [2], [9], [10]]
model = AgglomerativeClustering(n_clusters=2)
print(model.fit_predict(X))K-means
K-means splits data into K groups by minimizing distance to cluster centers.
Pick K with domain knowledge or elbow method.
Real-life example: K-means is seating guests at K tables so friends sit near their table center.
from sklearn.cluster import KMeans
X = [[1], [2], [10], [11]]
model = KMeans(n_clusters=2, random_state=42, n_init=10)
print(model.fit_predict(X))KNN (K-Nearest Neighbors)
KNN classifies by majority vote of K nearest training points — simple and strong baseline.
Scale features first; odd K avoids ties in binary classification.
Real-life example: KNN is asking your five nearest neighbors who they voted for — majority wins.
from sklearn.neighbors import KNeighborsClassifier
X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 1]
model = KNeighborsClassifier(n_neighbors=3).fit(X, y)
print(model.predict([[3.5]]))Grid Search
GridSearchCV tries hyperparameter combinations (K, depth, etc.) with cross-validation.
Finds better settings than manual guessing.
Real-life example: Grid search is tasting every spice combo on a small sample before cooking the full pot.
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 1]
grid = GridSearchCV(
KNeighborsClassifier(), {"n_neighbors": [1, 3, 5]}, cv=3
)
grid.fit(X, y)
print(grid.best_params_)Cross Validation
K-fold CV rotates train/test splits — more stable score than one split.
cross_val_score reports mean accuracy across folds.
Real-life example: Cross validation is five mock exams before boards — average score is more trustworthy than one lucky paper.
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 1]
scores = cross_val_score(DecisionTreeClassifier(), X, y, cv=3)
print(scores.mean())Bootstrap Aggregation
Bagging trains many models on random samples and averages votes — RandomForest is the famous example.
Reduces overfitting vs single deep trees.
Real-life example: Bootstrap aggregation is asking many doctors for diagnosis and taking the common answer.
from sklearn.ensemble import RandomForestClassifier
X = [[1], [2], [3], [4], [5], [6]]
y = [0, 0, 0, 1, 1, 1]
model = RandomForestClassifier(n_estimators=50, random_state=42)
model.fit(X, y)
print(model.predict([[2.5]]))Categorical Data
ML models need numbers. Encode categories with OneHotEncoder or pandas get_dummies().
Never feed raw strings like 'red', 'blue' directly into sklearn estimators.
Real-life example: Categorical encoding is converting city names to numbered tickets before sorting machines can process them.
import pandas as pd
df = pd.DataFrame({"color": ["red", "blue", "red"]})
encoded = pd.get_dummies(df)
print(encoded)Python Lists and Arrays
Python lists are dynamic arrays — O(1) index access, O(n) insert in middle.
Many DSA tutorials use lists before custom structures.
Real-life example: A list is a numbered locker row — open locker 5 instantly, but shifting lockers takes work.
arr = [7, 12, 9, 4, 11]
print(min(arr))Stacks
Stack: Last In, First Out (LIFO). Push adds top; pop removes top.
Use for undo history, browser back stack, expression parsing.
Real-life example: A stack of plates — you add and remove from the top only.
stack = []
stack.append(1)
stack.append(2)
print(stack.pop()) # 2Queues
Queue: First In, First Out (FIFO). enqueue back, dequeue front.
collections.deque is efficient for queue operations.
Real-life example: A ticket queue — first person in line gets served first.
from collections import deque
q = deque()
q.append("A")
q.append("B")
print(q.popleft()) # ALinked Lists
Linked lists chain nodes with data + next pointer. Insert/delete at head is O(1).
Python has no built-in linked list — implement with classes for learning.
Real-life example: A treasure hunt — each clue points to the next location, no numbered index.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
head = Node(1, Node(2, Node(3)))
print(head.next.data) # 2Hash Tables
Hash tables (dict in Python) map keys to values in average O(1) lookup.
Collisions handled internally — you use dict and set daily.
Real-life example: A hash table is a coat check — ticket number maps to your jacket instantly.
cache = {"user:1": "Aarav", "user:2": "Meera"}
print(cache["user:1"])Trees
Trees are hierarchical — one root, child nodes, no cycles. File systems and HTML DOM are trees.
Traversal: preorder, inorder, postorder visit nodes in different orders.
Real-life example: A company org chart is a tree — CEO at root, teams as branches.
Graphs
Graphs have nodes (vertices) and edges — may be cyclic. Social networks and maps are graphs.
Represent with adjacency list: dict mapping node → neighbors.
Real-life example: A city road map is a graph — intersections are nodes, roads are edges.
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A"],
"D": ["B"],
}
print(graph["A"])Binary Trees
Each node has at most two children — left and right. Basis for BSTs and heaps.
Binary trees power expression parsers and decision structures.
Real-life example: Binary choices at each step — yes/no questions forming a twenty-questions game tree.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = TreeNode(10, TreeNode(5), TreeNode(15))
print(root.left.val)Binary Search Trees
BST: left child < node < right child. Enables O(log n) search when balanced.
Inorder traversal of BST prints sorted values.
Real-life example: BST is a sorted filing cabinet — go left for smaller names, right for larger.
def search(node, target):
if not node:
return False
if target == node.val:
return True
if target < node.val:
return search(node.left, target)
return search(node.right, target)AVL Trees
AVL trees self-balance after inserts — height difference of subtrees ≤ 1.
Guarantees O(log n) operations vs skewed BST.
Real-life example: AVL is a self-leveling shelf — when one side gets too heavy, it rebalances automatically.
Linear Search
Linear search checks each element until found — O(n) time, works on unsorted data.
Simple and fine for small lists.
Real-life example: Finding socks in an messy drawer — check one item at a time left to right.
def linear_search(arr, target):
for i, val in enumerate(arr):
if val == target:
return i
return -1
print(linear_search([4, 2, 7, 1], 7))Binary Search
Binary search needs sorted data — halve the search space each step — O(log n).
Classic interview algorithm; implement with left/right pointers.
Real-life example: Finding a word in a dictionary — open middle, go left or right, repeat.
def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7))Bubble Sort
Bubble sort swaps adjacent pairs until sorted — O(n²), teaching tool only.
Real-life example: Bubble sort is bubbles rising — largest values float to the top each pass.
def bubble_sort(arr):
a = arr[:]
for i in range(len(a)):
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
print(bubble_sort([5, 1, 4, 2]))Selection Sort
Selection sort finds minimum of unsorted part, swaps to front — O(n²).
Real-life example: Selection sort is picking the shortest person each round for a height lineup.
def selection_sort(arr):
a = arr[:]
for i in range(len(a)):
m = i
for j in range(i + 1, len(a)):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
return a
print(selection_sort([5, 1, 4, 2]))Insertion Sort
Insertion sort grows sorted section by inserting each new card — O(n²) worst, good on nearly sorted data.
Real-life example: Sorting playing cards in hand — insert each new card into the right spot.
def insertion_sort(arr):
a = arr[:]
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
print(insertion_sort([5, 1, 4, 2]))Quick Sort
Quick sort picks pivot, partitions smaller/larger, recurses — average O(n log n).
Python's sorted() uses Timsort; learn quicksort for interviews.
Real-life example: Quicksort is dividing a pile into below/above a chosen weight, then sorting each pile.
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
mid = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + mid + quick_sort(right)
print(quick_sort([5, 1, 4, 2, 2]))Merge Sort
Merge sort splits in half, sorts each, merges — O(n log n) guaranteed, stable.
Real-life example: Merge sort is two sorted lines of people merging into one by comparing front heads.
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(a, b):
out, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
return out + a[i:] + b[j:]
print(merge_sort([5, 1, 4, 2]))Python MySQL — Get Started
MySQL is a popular relational database. Python connects via mysql-connector-python or PyMySQL.
Install: pip install mysql-connector-python. You need a running MySQL server.
Real-life example: MySQL is a filing room with labeled cabinets — Python is the clerk fetching files.
Create Connection
mysql.connector.connect(host, user, password, database) opens a session.
Use environment variables for passwords — never commit secrets.
Real-life example: Connection is your ID badge — without it, the database door stays locked.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
)
print(mydb.is_connected())Create Database
cursor.execute('CREATE DATABASE IF NOT EXISTS knowvora') creates a schema.
mydb.commit() saves DDL changes when autocommit is off.
Real-life example: Creating a database is opening a new warehouse wing for one project's boxes.
import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", password="pass")
cur = mydb.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS knowvora")
print("Database ready")Create Table
CREATE TABLE defines columns and types — INT, VARCHAR, DATE, PRIMARY KEY.
Switch to database with database='knowvora' in connect or USE knowvora.
Real-life example: A table is one spreadsheet tab with fixed column headers.
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
score INT
)
""")Insert
INSERT INTO adds rows. Parameterized queries (%s) prevent SQL injection.
executemany() bulk-inserts efficiently.
Real-life example: Insert is adding a new row to the attendance register.
sql = "INSERT INTO students (name, score) VALUES (%s, %s)"
cur.execute(sql, ("Riya", 92))
mydb.commit()Select
SELECT * FROM students fetches rows. fetchall(), fetchone(), fetchmany() read results.
Real-life example: Select is photocopying rows you need from the register.
cur.execute("SELECT name, score FROM students")
for row in cur.fetchall():
print(row)Where
WHERE filters rows — score > 80, name = 'Riya'. Combine with AND, OR.
Real-life example: Where is a search filter — only students from Section A.
cur.execute("SELECT * FROM students WHERE score >= %s", (90,))
print(cur.fetchall())Order By
ORDER BY score DESC sorts results. Default is ascending.
Real-life example: Order By is ranking students by marks on the notice board.
cur.execute("SELECT name, score FROM students ORDER BY score DESC")
print(cur.fetchall())Update
UPDATE students SET score = %s WHERE id = %s changes existing rows.
Always use WHERE on update — missing WHERE updates every row.
Real-life example: Update is correcting one student's score after re-checking the paper.
cur.execute("UPDATE students SET score = %s WHERE name = %s", (95, "Riya"))
mydb.commit()Delete
DELETE FROM students WHERE id = %s removes matching rows.
Real-life example: Delete is erasing one line from the register — confirm the right row first.
cur.execute("DELETE FROM students WHERE score < %s", (50,))
mydb.commit()Drop
DROP TABLE students removes the whole table structure and data.
Real-life example: Drop is shredding an entire spreadsheet tab — not just clearing cells.
cur.execute("DROP TABLE IF EXISTS old_students")Limit
LIMIT 10 returns only first N rows — pagination with OFFSET.
Real-life example: Limit is reading only the top 10 headlines, not the whole newspaper.
cur.execute("SELECT * FROM students ORDER BY score DESC LIMIT 5")
print(cur.fetchall())Join
JOIN combines tables on matching keys — INNER JOIN most common.
Real-life example: Join is matching student IDs in one sheet with course names in another.
cur.execute("""
SELECT students.name, courses.title
FROM students
INNER JOIN enrollments ON students.id = enrollments.student_id
INNER JOIN courses ON courses.id = enrollments.course_id
""")Python MongoDB — Get Started
MongoDB stores JSON-like documents. Python uses PyMongo: pip install pymongo.
Atlas free tier or local MongoDB for practice.
Real-life example: MongoDB is a flexible notebook — each page (document) can have different fields.
Create Database
MongoDB creates database on first write. client['knowvora'] selects or creates.
Real-life example: Naming a database is labeling a new shelf — items appear when you store the first box.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["knowvora"]
print(db.name)Create Collection
Collections group documents — like tables without fixed schema.
db.create_collection('students') or implicit on insert.
Real-life example: A collection is a folder of similar forms — job applications, receipts, etc.
students = db["students"]
# or db.create_collection("students")Insert
insert_one({}) and insert_many([]) add documents with _id auto-generated.
Real-life example: Insert is dropping a new form into the folder.
students = db["students"]
result = students.insert_one({"name": "Aarav", "score": 88})
print(result.inserted_id)Find
find() returns a cursor; find_one() first match. Empty filter {} gets all.
Real-life example: Find is searching the folder for every form with score above 80.
for doc in students.find({"score": {"$gte": 80}}):
print(doc)Query
Query operators: $gt, $lt, $in, $regex. Combine with $and, $or.
Real-life example: Query is advanced search — name starts with A AND score > 70.
query = {"name": {"$regex": "^A"}, "score": {"$gt": 70}}
print(list(students.find(query)))Sort
sort('score', -1) orders descending. 1 = ascending.
Real-life example: Sort is arranging forms by highest score on top.
for doc in students.find().sort("score", -1):
print(doc["name"], doc["score"])Update
update_one(filter, {'$set': {...}}) changes fields. $inc increments numbers.
Real-life example: Update is correcting one field on a form without rewriting the whole page.
students.update_one(
{"name": "Aarav"},
{"$set": {"score": 92}},
)Delete
delete_one(filter) and delete_many(filter) remove documents.
Real-life example: Delete is throwing away outdated forms — keep backups in production.
students.delete_many({"score": {"$lt": 50}})Drop
drop() removes entire collection. drop_database() removes whole DB — dangerous.
Real-life example: Drop is shredding the whole folder, not one paper.
students.drop()Limit
limit(5) caps results — pair with sort() for top-N queries.
Real-life example: Limit is reading only the first five sorted results.
top = students.find().sort("score", -1).limit(3)
print(list(top))Final Project — Student Analytics CLI
Build a CLI that loads student JSON, computes stats, saves to MySQL or MongoDB, and plots scores with Matplotlib.
Combines files, OOP, databases, and visualization from this full course.
Real-life example: A school admin tool — import marks, store in DB, print chart for principal.
import json
import statistics
import matplotlib.pyplot as plt
with open("students.json", encoding="utf-8") as f:
data = json.load(f)
scores = [s["score"] for s in data]
print("Average:", statistics.mean(scores))
plt.bar([s["name"] for s in data], scores)
plt.title("Class Scores")
plt.show()Interview & Examples Path
After 40 lessons: practice /mcq/python-mcq, /interview/python-interview, and rebuild the final project without notes.
Review the examples in earlier lessons for one-liners on lists, RegEx, files, and sklearn.
Real-life example: Interview prep is dress rehearsal — same skills as the job stage, lower stakes.
- Know list/dict complexity and when to use set
- Explain train/test split and overfitting in plain English
- Write connect → insert → select for MySQL and MongoDB from memory
- Ship the student analytics CLI as your portfolio piece
Key Takeaways
- Python reads like English — master syntax, types, and collections before frameworks.
- OOP, files, and modules organize real scripts; virtualenv keeps projects isolated.
- NumPy, Pandas, Matplotlib, and library intros open data and web paths.
- ML overview: explore data, preprocess, train/test, then regression, trees, and KNN.
- DSA overview: structures from stacks to AVL trees and sorts from bubble to merge.
- MySQL and MongoDB with Python store app data — SQL tables vs flexible documents.
- Finish with the student analytics project, MCQs, and interview practice.
Frequently Asked Questions
- Do I need math to learn Python?
- No for basics. Simple statistics helps for the ML overview section. Deep math is only required for advanced ML research roles.
- Should I learn Python before Django or ML?
- Yes. Finish basics, OOP, files, and modules first. Django and scikit-learn assume you already know functions, classes, and pip.
- MySQL or MongoDB with Python?
- MySQL fits structured relational data with joins. MongoDB fits flexible JSON documents. Many apps use both for different jobs.
- Does this cover a complete beginner-to-pro Python path?
- Yes — this course covers core Python, OOP, files, modules, Matplotlib, ML overview, DSA overview, MySQL, and MongoDB across 40 lessons.
- Is Python good for jobs?
- Yes. Python is widely used in backend development, automation, data analysis, and AI — one of the most employable languages worldwide.