Python Introduction
Python is a popular, high-level, general-purpose programming language created by Guido van Rossum and released in 1991.
What can Python do?
- ✅ Web development (server-side) — Flask, Django, FastAPI
- ✅ Data Science & Machine Learning — NumPy, Pandas, TensorFlow
- ✅ Automation & Scripting
- ✅ Game development
- ✅ Desktop GUI apps (Tkinter, PyQt)
- ✅ Connect to databases — MySQL, MongoDB, PostgreSQL
Why Python?
- 🌐 Works on Windows, Mac, Linux, Raspberry Pi
- 📝 Simple syntax similar to English
- ⚡ Fewer lines of code than Java/C++
- 🔄 Runs on an interpreter — instant testing
- 🎯 Supports procedural, OOP, and functional styles
Your First Python Program
🔎 Extra Detailed Explanation
Beginner View
Python is not only a beginner language. Think of it as a practical tool used to solve many types of problems: automation, backend APIs, cloud scripting, data processing, AI/ML, testing, and DevOps tasks.
Developer View
A Python developer should learn the full workflow: write code, split logic into functions/modules, use virtual environments, install packages, write tests, handle errors, log events, and deploy the app.
Production Scope
In production, Python is used inside APIs, Docker containers, AWS Lambda functions, scheduled jobs, data pipelines, ML notebooks, and internal tools.
More Practical Example
def greet(name):
return f"Hello {name}, welcome to Python!"
message = greet("Anu")
print(message)Common Mistakes
- Thinking print-only scripts are enough for real projects. Learn functions, files, APIs, and testing too.
- Ignoring project structure. Real apps need separate files for routes, services, models, and tests.
- Installing every package globally instead of using a virtual environment.
Practice Task
Install Python
Step 1: Check if Python is Already Installed
Step 2: Download Python
Go to 👉 https://www.python.org/downloads/ and download the latest version (3.12+).
Step 3: Verify Installation
Step 4: Run Python
Best IDEs for Python
| IDE | Best For |
|---|---|
| VS Code | All-purpose (recommended) |
| PyCharm | Large projects, Django |
| Jupyter Notebook | Data Science, ML |
| IDLE | Beginners (built-in) |
🔎 Extra Detailed Explanation
Beginner View
Installation is not only downloading Python. You must also confirm Python and pip commands work from terminal, then set up an editor and virtual environment.
Developer View
Professional setup includes Python, pip, virtual environment, VS Code/PyCharm, Git, formatter, linter, and a clean project folder.
Production Scope
Use fixed Python versions for projects. In Docker or CI/CD, specify the Python version explicitly.
More Practical Example
python --version python -m pip --version python -m venv .venv # Windows: .venv\Scripts\activate # macOS/Linux: source .venv/bin/activate python -m pip install requests
Common Mistakes
- Forgetting "Add Python to PATH" on Windows.
- Using pip command from another Python installation. Prefer python -m pip.
- Installing packages before activating virtual environment.
Practice Task
Python Syntax
1️⃣ Execute Python Syntax
2️⃣ Indentation (VERY IMPORTANT)
Python uses indentation (spaces at start of line) to indicate a block of code.
3️⃣ Python Variables
4️⃣ Case Sensitive
🔎 Extra Detailed Explanation
Beginner View
Syntax means the grammar of Python. Python uses indentation to identify code blocks, so spaces are meaningful.
Developer View
Consistent indentation makes code readable and avoids logic bugs. Use 4 spaces, a formatter like Black, and avoid mixing tabs/spaces.
Production Scope
Code style consistency matters in teams. Use formatting and linting in CI/CD to catch syntax and style problems before deployment.
More Practical Example
score = 85
if score >= 80:
print("Excellent")
print("Certificate eligible")
else:
print("Keep practicing")
print("Done")Common Mistakes
- Missing colon after if/for/while/def/class.
- Wrong indentation causing code to run outside the intended block.
- Mixing tabs and spaces.
Practice Task
Python Comments
Comments explain code, make it readable, and prevent execution while testing.
1️⃣ Single-Line Comment
2️⃣ Multi-Line Comment
3️⃣ Multi-Line Strings as Comments
🔎 Extra Detailed Explanation
Beginner View
Comments are notes for humans. Python ignores comments during execution.
Developer View
Good comments explain why something is done, not just what the code already shows. Use docstrings for functions/classes/modules.
Production Scope
Clear comments and docstrings help new developers understand business rules, assumptions, edge cases, and public APIs.
More Practical Example
def calculate_discount(price, percentage):
"""Return price after applying discount percentage."""
# Business rule: negative discount is treated as zero.
if percentage < 0:
percentage = 0
return price - (price * percentage / 100)
print(calculate_discount(1000, 10))Common Mistakes
- Writing comments that repeat obvious code.
- Leaving outdated comments after changing logic.
- Using triple-quoted strings everywhere instead of real comments/docstrings.
Practice Task
Python Variables
Variables are containers for storing data values. Python has no command for declaring a variable — it's created the moment you assign a value.
1️⃣ Creating Variables
2️⃣ Variables Can Change Type
3️⃣ Casting (Specify the type)
4️⃣ Get the Type
5️⃣ Variable Naming Rules
- ✅ Must start with a letter or underscore (_)
- ❌ Cannot start with a number
- ✅ Can contain letters, numbers, underscores
- ⚠️ Case-sensitive (age, Age, AGE are different)
- ❌ Cannot use Python keywords (if, for, class, etc.)
6️⃣ Multi-word Variable Naming Styles
7️⃣ Assign Multiple Values
8️⃣ Output Variables
9️⃣ Global Variables
🚀 Real-Time Example: User Profile
🔎 Extra Detailed Explanation
Beginner View
A variable is a name attached to a value. You do not declare a type first; Python detects the type from the assigned value.
Developer View
Python variables are references to objects. Assignment does not always copy data, especially for mutable objects like lists and dictionaries.
Production Scope
Use clear names like user_email, total_amount, is_active. Avoid x, y, data1 except in tiny examples.
More Practical Example
user_name = "Anu"
age = 22
skills = ["Python", "AWS"]
same_skills = skills
same_skills.append("SQL")
print(user_name)
print(skills)Common Mistakes
- Using reserved keywords as variable names.
- Using unclear names in business code.
- Expecting list assignment to create a deep copy.
Practice Task
Python Data Types
Python has several built-in data types categorized into groups:
| Category | Data Types |
|---|---|
| Text | str |
| Numeric | int, float, complex |
| Sequence | list, tuple, range |
| Mapping | dict |
| Set | set, frozenset |
| Boolean | bool |
| Binary | bytes, bytearray |
| None | NoneType |
Get Data Type
Setting Data Types — All Examples
🔎 Extra Detailed Explanation
Beginner View
Data type means what kind of value you are storing: text, number, boolean, list, dictionary, set, tuple, or None.
Developer View
Use the right type for the job: list for ordered items, set for unique items, dict for key-value data, tuple for fixed records, Decimal for money.
Production Scope
Correct types make validation, storage, APIs, and database mapping easier.
More Practical Example
values = ["text", 10, 10.5, True, None, [1, 2], {"id": 1}, {1, 2}, (1, 2)]
for value in values:
print(type(value).__name__, "=>", value)Common Mistakes
- Using float for money.
- Using list when uniqueness is needed.
- Confusing None with False or empty string.
Practice Task
Python Numbers
There are 3 numeric types in Python: int, float, complex.
1️⃣ int — Integer (whole number)
2️⃣ float — Decimal number
3️⃣ complex — Complex number
4️⃣ Type Conversion
5️⃣ Random Numbers
🚀 Real-Time: Calculator
🔎 Extra Detailed Explanation
Beginner View
Python numbers include integers, decimal-like floats, and complex numbers.
Developer View
Float uses binary floating point and can have precision surprises. Use Decimal for money.
Production Scope
For invoices, banking, tax, and currency, use Decimal. For ML, science, and measurement data, float is usually acceptable.
More Practical Example
from decimal import Decimal
print(0.1 + 0.2)
print(Decimal("0.1") + Decimal("0.2"))
price = Decimal("99.99")
qty = 3
total = price * qty
print(total)Common Mistakes
- Using float for financial totals.
- Confusing / and //.
- Using random for passwords instead of secrets.
Practice Task
Python Casting
Casting = converting a variable from one type to another.
1️⃣ int() — Convert to Integer
2️⃣ float() — Convert to Float
3️⃣ str() — Convert to String
🚀 Real-Time: User Input Calculator
🔎 Extra Detailed Explanation
Beginner View
Casting converts one type to another, like string to int.
Developer View
Casting can fail, so production code validates input and catches ValueError.
Production Scope
APIs and forms receive text/JSON; convert and validate before using the values in calculations or database queries.
More Practical Example
def safe_int(value, default=0):
try:
return int(value)
except (TypeError, ValueError):
return default
print(safe_int("100"))
print(safe_int("abc"))
print(safe_int(None))Common Mistakes
- Using bool("False") expecting False; non-empty strings are True.
- Using int("10.5") directly.
- Not handling invalid user input.
Practice Task
Python Strings
1️⃣ Create String
2️⃣ Multiline String
3️⃣ Strings as Arrays
4️⃣ String Slicing
5️⃣ String Length
6️⃣ Check String — in / not in
7️⃣ Concatenate Strings
8️⃣ Format Strings — f-string (Best Way)
9️⃣ Escape Characters
| Code | Meaning |
|---|---|
\' | Single quote |
\" | Double quote |
\\ | Backslash |
\n | New line |
\t | Tab |
🔟 ALL String Methods (Quick List)
| Method | Description |
|---|---|
| capitalize() | First char uppercase |
| upper() / lower() | Change case |
| title() | Title Case |
| swapcase() | Swap upper/lower |
| strip() / lstrip() / rstrip() | Remove whitespace |
| replace(a, b) | Replace a with b |
| split(x) | Split into list |
| join(list) | Join list with string |
| find(x) / index(x) | Find position |
| count(x) | Count occurrences |
| startswith(x) / endswith(x) | Check start/end |
| isalpha() / isdigit() / isalnum() | Type checks |
| isupper() / islower() | Case checks |
| zfill(w) | Pad with zeros |
| center(w) | Center align |
String Methods in Action
🚀 Real-Time: Username Validator
🔎 Extra Detailed Explanation
Beginner View
A string stores text. Strings are immutable, meaning methods return a new string instead of changing the original.
Developer View
Learn indexing, slicing, f-strings, encoding, cleanup, validation, and string methods.
Production Scope
Strings are used heavily in APIs, forms, logs, file paths, CSVs, emails, and database fields.
More Practical Example
email = " ANU@Example.COM "
clean = email.strip().lower()
print(clean)
print(clean.endswith(".com"))
print(clean.split("@"))
print(f"Email domain: {clean.split('@')[1]}")Common Mistakes
- Forgetting strip() before validation.
- Using + for large repeated string building; use join().
- Thinking replace() modifies original string.
Practice Task
Python Booleans
Booleans represent True or False.
1️⃣ Boolean Values
2️⃣ bool() Function
3️⃣ Falsy Values
False,None,0,0.0""(empty string)[](empty list){}(empty dict)()(empty tuple)
🚀 Real-Time: Login Check
🔎 Extra Detailed Explanation
Beginner View
Booleans are True or False, but Python also treats empty values as False and non-empty values as True.
Developer View
Truthiness is useful, but be careful when 0, empty string, or empty list are valid values.
Production Scope
Use explicit checks like value is None when None means missing but 0 is allowed.
More Practical Example
values = ["hello", "", 0, 1, [], [1], None]
for value in values:
print(repr(value), bool(value))Common Mistakes
- Using if value when 0 is a valid value.
- Comparing to True with == True.
- Confusing string "False" with boolean False.
Practice Task
Python Operators
1️⃣ Arithmetic Operators
| Op | Name | Example |
|---|---|---|
| + | Addition | x + y |
| - | Subtraction | x - y |
| * | Multiplication | x * y |
| / | Division | x / y |
| % | Modulus | x % y |
| ** | Exponent | x ** y |
| // | Floor Division | x // y |
2️⃣ Assignment Operators
3️⃣ Comparison Operators
| Op | Meaning |
|---|---|
| == | Equal |
| != | Not Equal |
| > | Greater than |
| < | Less than |
| >= | Greater or equal |
| <= | Less or equal |
4️⃣ Logical Operators
5️⃣ Identity Operators (is, is not)
6️⃣ Membership Operators (in, not in)
7️⃣ Bitwise Operators
| Op | Name |
|---|---|
| & | AND |
| | | OR |
| ^ | XOR |
| ~ | NOT |
| << | Left Shift |
| >> | Right Shift |
🚀 Real-Time: BMI Calculator
🔎 Extra Detailed Explanation
Beginner View
Operators perform calculations, comparisons, membership checks, identity checks, and logical decisions.
Developer View
Understand == vs is, / vs //, and operator precedence. Use parentheses for clarity.
Production Scope
Operators power validation, pricing, authorization, search filters, and business rules.
More Practical Example
price = 1000 is_premium = True coupon_valid = False discount_allowed = is_premium or coupon_valid final_price = price * 0.9 if discount_allowed else price print(discount_allowed) print(final_price)
Common Mistakes
- Using is for value equality.
- Using = instead of == in conditions.
- Relying on complex precedence instead of parentheses.
Practice Task
Python Lists
Lists are ordered, changeable, and allow duplicates. Created with [ ].
1️⃣ Create a List
2️⃣ Mixed Types
3️⃣ Access Items
4️⃣ Check if Exists
5️⃣ Change Items
6️⃣ Add Items
7️⃣ Remove Items
8️⃣ Loop Through List
9️⃣ List Comprehension
🔟 Sort List
1️⃣1️⃣ Copy List
1️⃣2️⃣ Join Lists
1️⃣3️⃣ All List Methods
| Method | Description |
|---|---|
| append() | Add at end |
| insert() | Add at index |
| extend() | Add multiple |
| remove() | Remove by value |
| pop() | Remove by index |
| clear() | Empty list |
| index() | Find position |
| count() | Count occurrences |
| sort() | Sort ascending |
| reverse() | Reverse order |
| copy() | Copy list |
🚀 Real-Time: Shopping Cart
🔎 Extra Detailed Explanation
Beginner View
A list is an ordered, changeable collection. It can store multiple values.
Developer View
Know list methods, slicing, comprehensions, mutability, shallow copy vs deep copy.
Production Scope
Lists hold API results, rows, tasks, form items, batch records, and report data.
More Practical Example
tasks = []
tasks.append("learn Python")
tasks.append("build API")
tasks.insert(1, "practice lists")
for i, task in enumerate(tasks, start=1):
print(i, task)
completed = tasks.pop(0)
print("Completed:", completed)
print("Pending:", tasks)Common Mistakes
- Modifying a list while looping over it.
- Using list as default argument.
- Using list for unique membership where set is better.
Practice Task
Python Tuples
Tuples are ordered, unchangeable, allow duplicates. Created with ( ).
1️⃣ Create Tuple
2️⃣ One Item Tuple (need comma!)
3️⃣ Access Tuple Items
4️⃣ Update Tuple (Trick: convert to list)
5️⃣ Unpacking Tuples
6️⃣ Loop Tuple
7️⃣ Join Tuples
8️⃣ Tuple Methods
| Method | Description |
|---|---|
| count() | Count occurrences |
| index() | Find position |
🚀 Real-Time: GPS Coordinates
🔎 Extra Detailed Explanation
Beginner View
A tuple is an ordered collection that cannot be changed after creation.
Developer View
Use tuples for fixed records, multiple return values, coordinates, and immutable groupings.
Production Scope
Tuples are useful where accidental modification should be avoided.
More Practical Example
def min_max_avg(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = min_max_avg([10, 20, 30])
print(low, high, avg)
single = ("apple",)
print(type(single).__name__)Common Mistakes
- Forgetting comma in one-item tuple.
- Using tuple for complex records where dataclass is clearer.
- Assuming tuple makes nested lists immutable.
Practice Task
Python Sets
Sets are unordered, unchangeable*, no duplicates. Created with { }.
1️⃣ Create Set
2️⃣ Duplicates Removed Automatically
3️⃣ Access (No Index — Use Loop)
4️⃣ Add Items
5️⃣ Remove Items
6️⃣ Set Operations (Union, Intersection, Difference)
7️⃣ Subset / Superset
8️⃣ All Set Methods
| Method | Description |
|---|---|
| add() | Add element |
| update() | Add multiple |
| remove() | Remove (error if not found) |
| discard() | Remove (no error) |
| pop() | Remove random |
| clear() | Empty set |
| copy() | Copy set |
| union() | Combine |
| intersection() | Common items |
| difference() | Items in A not B |
| issubset() | A ⊆ B? |
| issuperset() | A ⊇ B? |
🚀 Real-Time: Remove Duplicates from List
🔎 Extra Detailed Explanation
Beginner View
A set stores unique values and automatically removes duplicates.
Developer View
Use sets for fast membership tests and group operations such as union, intersection, difference.
Production Scope
Sets are great for duplicate removal, permission checks, compare old/new IDs, and validation.
More Practical Example
expected = {"S101", "S102", "S103"}
submitted = {"S101", "S103", "S104"}
print("Completed:", expected & submitted)
print("Missing:", expected - submitted)
print("Extra:", submitted - expected)Common Mistakes
- Expecting set order.
- Adding unhashable values like lists.
- Using remove() when value may not exist; discard() is safer.
Practice Task
Python Dictionaries
Dictionaries store data as key:value pairs. Ordered, changeable, no duplicate keys. Created with { }.
1️⃣ Create Dictionary
2️⃣ Access Values
3️⃣ Check if Key Exists
4️⃣ Change/Update Values
5️⃣ Add Items
6️⃣ Remove Items
7️⃣ Loop Through Dictionary
8️⃣ Copy Dictionary
9️⃣ Nested Dictionary
🔟 Dictionary Comprehension
1️⃣1️⃣ All Dictionary Methods
| Method | Description |
|---|---|
| get() | Get value (no error) |
| keys() | All keys |
| values() | All values |
| items() | All key-value pairs |
| update() | Update/add multiple |
| pop() | Remove by key |
| popitem() | Remove last |
| clear() | Empty dict |
| copy() | Copy dict |
| fromkeys() | Create from keys |
| setdefault() | Get/set default |
🚀 Real-Time: Student Database
🔎 Extra Detailed Explanation
Beginner View
A dictionary stores key-value pairs. It is like a real-world record with labels.
Developer View
Use dicts for API payloads, configs, lookup tables, grouping, and JSON-like data.
Production Scope
Dictionaries appear in every Python backend: request bodies, responses, database rows, config, cache, and logs.
More Practical Example
students = {
"S101": {"name": "Anu", "marks": 88},
"S102": {"name": "Ravi", "marks": 76},
}
sid = "S101"
student = students.get(sid)
if student:
print(student["name"], student["marks"])
for sid, info in students.items():
print(sid, info["name"])Common Mistakes
- Accessing missing keys directly when missing is expected.
- Using mutable objects as keys.
- Creating deeply nested dicts without structure.
Practice Task
Python If...Else
Python supports usual logical conditions: ==, !=, <, >, <=, >=
1️⃣ if Statement
2️⃣ elif
3️⃣ else
4️⃣ Short Hand If
5️⃣ and / or / not
6️⃣ Nested If
7️⃣ pass Statement
🚀 Real-Time: Grade Calculator
🔎 Extra Detailed Explanation
Beginner View
if/elif/else lets your program make decisions. Python checks conditions from top to bottom.
Developer View
Order matters. Put specific conditions first and use early return to reduce nesting.
Production Scope
Decision logic is everywhere: login, payment, approval, validation, pricing, routing, and error handling.
More Practical Example
marks = 83
attendance = 76
if marks >= 80 and attendance >= 75:
result = "Distinction"
elif marks >= 40 and attendance >= 60:
result = "Pass"
elif attendance < 60:
result = "Attendance shortage"
else:
result = "Fail"
print(result)Common Mistakes
- Putting general conditions before specific conditions.
- Using too many nested if blocks.
- Forgetting final else for unexpected cases.
Practice Task
Python While Loop
Execute a set of statements as long as a condition is true.
1️⃣ Basic While
2️⃣ break Statement
3️⃣ continue Statement
4️⃣ else with While
🚀 Real-Time: Number Guessing
🔎 Extra Detailed Explanation
Beginner View
A while loop repeats while a condition is True.
Developer View
Use while when the number of repetitions is not known. Always provide a clear stop condition.
Production Scope
Common in retry loops, polling jobs, menu loops, and streaming reads.
More Practical Example
attempt = 0
max_attempts = 3
success = False
while attempt < max_attempts and not success:
attempt += 1
print("Trying", attempt)
if attempt == 2:
success = True
print("Success:", success)Common Mistakes
- Infinite loops without timeout.
- Forgetting to update loop variable.
- Using while when for is simpler.
Practice Task
Python For Loop
Iterate over a sequence (list, tuple, dict, set, string).
1️⃣ Loop Through List
2️⃣ Loop Through String
3️⃣ break / continue
4️⃣ range() Function
5️⃣ else with For
6️⃣ Nested For
7️⃣ enumerate()
8️⃣ zip()
🚀 Real-Time: Multiplication Table
🔎 Extra Detailed Explanation
Beginner View
A for loop visits each item in a sequence or iterable.
Developer View
Use enumerate for index, zip for parallel lists, items() for dictionaries, and comprehensions for simple transformations.
Production Scope
for loops process records, files, API data, database rows, and batches.
More Practical Example
names = ["Anu", "Ravi", "Priya"]
marks = [88, 76, 91]
for index, (name, mark) in enumerate(zip(names, marks), start=1):
grade = "A" if mark >= 80 else "B"
print(index, name, mark, grade)Common Mistakes
- Using range(len(items)) when enumerate is cleaner.
- Changing a list while looping through it.
- Assuming dictionary iteration gives values; it gives keys.
Practice Task
Python Match Case (Python 3.10+)
Like switch-case in other languages.
1️⃣ Basic Match
2️⃣ Default Case
3️⃣ Combine Cases (|)
4️⃣ Match with Guards (if)
🚀 Real-Time: HTTP Status
🔎 Extra Detailed Explanation
Beginner View
match/case is Python’s switch-like feature for matching values and patterns.
Developer View
Use match for command routers, status mapping, structured events, and payload patterns.
Production Scope
Useful in event-driven systems, API status handling, parsers, and CLI command handling.
More Practical Example
command = "delete"
match command:
case "create":
print("Create resource")
case "update":
print("Update resource")
case "delete":
print("Delete resource")
case _:
print("Unknown command")Common Mistakes
- Using match on Python below 3.10.
- Forgetting default case _.
- Using match for very simple if/else.
Practice Task
Python Functions
A function is a reusable block of code. Defined using def keyword.
1️⃣ Create & Call Function
2️⃣ Arguments / Parameters
3️⃣ Multiple Arguments
4️⃣ Default Parameter
5️⃣ Keyword Arguments
6️⃣ *args (Arbitrary Args)
7️⃣ **kwargs (Arbitrary Keyword Args)
8️⃣ Return Values
9️⃣ Type Hints
🚀 Real-Time: Tax Calculator
🔎 Extra Detailed Explanation
Beginner View
A function is reusable code with a name. It can accept inputs and return output.
Developer View
Functions should have one responsibility, meaningful names, type hints where useful, and tests.
Production Scope
Functions form service layers, validators, utilities, transformations, and business logic.
More Practical Example
def calculate_grade(marks):
if marks >= 90:
return "A+"
if marks >= 80:
return "A"
if marks >= 70:
return "B"
return "C"
print(calculate_grade(85))Common Mistakes
- Printing instead of returning when caller needs value.
- Too many responsibilities in one function.
- Using global variables instead of parameters.
Practice Task
Python Lambda
A small anonymous function — one-line, no name.
Syntax
lambda arguments : expression
1️⃣ Basic Lambda
2️⃣ Lambda Inside Function
3️⃣ Lambda with map()
4️⃣ Lambda with filter()
5️⃣ Lambda with sorted()
6️⃣ Lambda with reduce()
🔎 Extra Detailed Explanation
Beginner View
lambda creates a small one-line anonymous function.
Developer View
Use lambda mainly for short key functions in sorted, map, filter, and callbacks.
Production Scope
Keep lambdas simple. Complex logic should be a named function for readability and testing.
More Practical Example
students = [("Anu", 88), ("Ravi", 76), ("Priya", 91)]
by_marks = sorted(students, key=lambda item: item[1], reverse=True)
print(by_marks)
even = list(filter(lambda n: n % 2 == 0, [1, 2, 3, 4]))
print(even)Common Mistakes
- Writing long lambdas.
- Forgetting map/filter return iterators.
- Using lambda when def is clearer.
Practice Task
Python Decorators
A decorator is a function that modifies another function.
1️⃣ Basic Decorator
2️⃣ Decorator with Arguments
3️⃣ Real-Time: Timer Decorator
🔎 Extra Detailed Explanation
Beginner View
A decorator wraps a function and adds behavior before or after it.
Developer View
Decorators are used in frameworks, logging, timing, authentication, retries, caching, and validation.
Production Scope
Always use functools.wraps and keep decorator behavior predictable.
More Practical Example
from functools import wraps
def require_admin(func):
@wraps(func)
def wrapper(user, *args, **kwargs):
if not user.get("is_admin"):
return "Access denied"
return func(user, *args, **kwargs)
return wrapper
@require_admin
def delete_user(user):
return "User deleted"
print(delete_user({"is_admin": False}))
print(delete_user({"is_admin": True}))Common Mistakes
- Not returning result from wrapper.
- Not using functools.wraps.
- Hiding too much business logic inside decorators.
Practice Task
Python Generators
Generators yield values one at a time using yield — memory efficient.
1️⃣ Basic Generator
2️⃣ Range with Generator
3️⃣ Generator Expression
4️⃣ next() with Generator
🚀 Real-Time: Fibonacci Generator
🔎 Extra Detailed Explanation
Beginner View
A generator gives values one by one using yield instead of returning all values at once.
Developer View
Generators are memory efficient for large files, streams, pagination, and ETL pipelines.
Production Scope
Use generators when processing large data where building a full list is expensive.
More Practical Example
def batches(items, size):
for i in range(0, len(items), size):
yield items[i:i+size]
for batch in batches([1, 2, 3, 4, 5], 2):
print(batch)Common Mistakes
- Trying to reuse an exhausted generator.
- Converting huge generators to list.
- Using yield where a simple list is clearer.
Practice Task
Python Recursion
A function that calls itself to solve a problem.
1️⃣ Factorial
2️⃣ Fibonacci
3️⃣ Sum of List
4️⃣ Power Function
🔎 Extra Detailed Explanation
Beginner View
Recursion is a function calling itself.
Developer View
Every recursive function needs a base case and must move closer to that base case.
Production Scope
Use recursion for tree-like data, nested categories, folders, comments, and nested JSON.
More Practical Example
def sum_nested(items):
total = 0
for item in items:
if isinstance(item, list):
total += sum_nested(item)
else:
total += item
return total
print(sum_nested([1, [2, 3], [4, [5]]]))Common Mistakes
- No base case.
- Recursive call does not reduce problem.
- Using recursion for simple loops unnecessarily.
Practice Task
Python Classes & Objects
A class is a blueprint, an object is an instance of that class.
1️⃣ Create a Class
2️⃣ __init__() Constructor
3️⃣ __str__() Method
4️⃣ Object Methods
5️⃣ Modify / Delete Properties
6️⃣ pass Statement
🚀 Real-Time: Bank Account
🔎 Extra Detailed Explanation
Beginner View
A class is a blueprint; an object is created from that blueprint.
Developer View
Classes should group data and related behavior. Use them for domain objects and services.
Production Scope
Classes power models, API clients, services, repositories, config objects, and framework components.
More Practical Example
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def is_available(self):
return self.stock > 0
p = Product("Laptop", 55000, 3)
print(p.name)
print(p.is_available())Common Mistakes
- Forgetting self.
- Creating one giant class.
- Using classes when a simple function would be enough.
Practice Task
Python Inheritance
Inheritance lets a class inherit attributes/methods from another class.
1️⃣ Parent Class
2️⃣ Child Class
3️⃣ Child __init__() with super()
4️⃣ Multi-Level Inheritance
5️⃣ Multiple Inheritance
🚀 Real-Time: Vehicle System
🔎 Extra Detailed Explanation
Beginner View
Inheritance lets a child class reuse code from a parent class.
Developer View
Use inheritance for true is-a relationships; use composition for has-a relationships.
Production Scope
Inheritance appears in frameworks, base models, custom exceptions, and plugin systems.
More Practical Example
class Notification:
def send(self, message):
raise NotImplementedError
class EmailNotification(Notification):
def send(self, message):
return f"Email sent: {message}"
n = EmailNotification()
print(n.send("Welcome"))Common Mistakes
- Using inheritance only to share utility code.
- Forgetting super().__init__().
- Creating deep inheritance hierarchies.
Practice Task
Python Polymorphism
"Many forms" — same method name, different behavior.
1️⃣ Function Polymorphism
2️⃣ Class Method Polymorphism
3️⃣ Method Overriding
🚀 Real-Time: Shape Area
🔎 Extra Detailed Explanation
Beginner View
Polymorphism means different objects can respond to the same method name.
Developer View
This enables flexible designs where code depends on behavior, not exact class.
Production Scope
Common in payment gateways, notification providers, file exporters, storage adapters, and testing mocks.
More Practical Example
class PdfExporter:
def export(self):
return "PDF exported"
class CsvExporter:
def export(self):
return "CSV exported"
for exporter in [PdfExporter(), CsvExporter()]:
print(exporter.export())Common Mistakes
- Using many isinstance checks instead of common method names.
- Inconsistent method signatures.
- No clear interface documentation.
Practice Task
Python Encapsulation
Hiding data inside class — using private attributes.
1️⃣ Public, Protected, Private
2️⃣ Getter / Setter
3️⃣ @property Decorator
🔎 Extra Detailed Explanation
Beginner View
Encapsulation means keeping data safe inside a class and controlling how it changes.
Developer View
Use properties to validate values before assignment.
Production Scope
Useful for preventing invalid balance, negative price, invalid status, or unauthorized state changes.
More Practical Example
class Product:
def __init__(self, price):
self.price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("Price cannot be negative")
self._price = value
p = Product(100)
print(p.price)Common Mistakes
- Thinking _name is truly private.
- Using getters/setters everywhere unnecessarily.
- Putting slow API calls inside properties.
Practice Task
Magic / Dunder Methods
Methods with double underscores like __init__, __str__, etc.
Common Magic Methods
| Method | Purpose |
|---|---|
| __init__ | Constructor |
| __str__ | str(obj) / print(obj) |
| __repr__ | repr(obj) |
| __len__ | len(obj) |
| __add__ | obj1 + obj2 |
| __sub__ | obj1 - obj2 |
| __mul__ | obj1 * obj2 |
| __eq__ | obj1 == obj2 |
| __lt__ | obj1 < obj2 |
| __gt__ | obj1 > obj2 |
| __getitem__ | obj[i] |
| __setitem__ | obj[i] = x |
| __call__ | obj() |
| __del__ | Destructor |
Operator Overloading Example
__call__ Example
🔎 Extra Detailed Explanation
Beginner View
Dunder methods are special methods like __str__ and __len__ that Python calls automatically.
Developer View
Use them to make objects work naturally with print, len, equality, addition, iteration, and context managers.
Production Scope
Useful for domain value objects, custom collections, clean debugging, and developer-friendly APIs.
More Practical Example
class Cart:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def __len__(self):
return len(self.items)
def __str__(self):
return f"Cart({self.items})"
cart = Cart()
cart.add("Book")
print(len(cart))
print(cart)Common Mistakes
- Returning non-string from __str__.
- Making operators do surprising things.
- Not implementing __repr__ for debug-heavy objects.
Practice Task
Python File Handling
Use open() to work with files. Modes: r=read, w=write, a=append, x=create.
1️⃣ Read a File
2️⃣ Read with 'with' (Recommended)
3️⃣ Read Line by Line
4️⃣ Write to File
5️⃣ Append to File
6️⃣ Delete File
🚀 Real-Time: Log Writer
🔎 Extra Detailed Explanation
Beginner View
File handling means reading and writing files from Python.
Developer View
Use with open(...) to automatically close files. Specify encoding for text files.
Production Scope
Used for logs, reports, uploads, exports, configs, ETL, and local caches.
More Practical Example
from datetime import datetime
def write_log(message):
with open("app.log", "a", encoding="utf-8") as f:
f.write(f"{datetime.now()} - {message}\n")
write_log("Application started")
print("Logged")Common Mistakes
- Not closing files.
- Forgetting encoding.
- Overwriting files with w mode accidentally.
Practice Task
Python JSON
1️⃣ Parse JSON (string → dict)
2️⃣ Convert dict → JSON
3️⃣ Pretty Print
4️⃣ Read/Write JSON File
5️⃣ Conversion Table
| Python | JSON |
|---|---|
| dict | Object |
| list, tuple | Array |
| str | String |
| int, float | Number |
| True / False | true / false |
| None | null |
🔎 Extra Detailed Explanation
Beginner View
JSON is a common data format used by APIs and config files.
Developer View
Use loads/dumps for strings and load/dump for files. Validate external JSON before use.
Production Scope
Used in REST APIs, events, queues, configs, logs, and integrations.
More Practical Example
import json
user = {"name": "Anu", "skills": ["Python", "AWS"], "active": True}
text = json.dumps(user, indent=2)
print(text)
parsed = json.loads(text)
print(parsed["skills"][0])Common Mistakes
- Using eval to parse JSON.
- Trying to dump datetime directly.
- Forgetting JSON requires double quotes.
Practice Task
Python Try...Except
1️⃣ Basic Try-Except
2️⃣ Multiple Except Blocks
3️⃣ else Block
4️⃣ finally Block
5️⃣ Raise an Exception
6️⃣ Common Exception Types
| Exception | When |
|---|---|
| NameError | Variable not defined |
| TypeError | Wrong type used |
| ValueError | Right type, wrong value |
| IndexError | List index out of range |
| KeyError | Dict key not found |
| ZeroDivisionError | Division by 0 |
| FileNotFoundError | File not found |
🚀 Real-Time: Safe Division
🔎 Extra Detailed Explanation
Beginner View
Exceptions are errors. try/except lets your program handle expected errors gracefully.
Developer View
Catch specific exceptions, use else for success, finally for cleanup, and raise for invalid states.
Production Scope
Error handling is critical for APIs, files, DB calls, network calls, user input, and background jobs.
More Practical Example
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError:
return "Numbers required"
else:
return result
finally:
print("divide attempted")
print(divide(10, 2))
print(divide(10, 0))Common Mistakes
- Bare except hiding real bugs.
- Silently ignoring errors.
- Returning confusing mixed types without documentation.
Practice Task
Python Dates
1️⃣ Current Date & Time
2️⃣ Create Date
3️⃣ Format Dates
4️⃣ Format Codes
| Code | Meaning |
|---|---|
| %Y | Year (2024) |
| %m | Month (01-12) |
| %B | Month name |
| %d | Day (01-31) |
| %A | Weekday name |
| %H | Hour 24 |
| %M | Minute |
| %S | Second |
| %p | AM/PM |
5️⃣ Date Arithmetic
🚀 Real-Time: Age Calculator
🔎 Extra Detailed Explanation
Beginner View
datetime helps work with dates, times, formatting, and durations.
Developer View
Use timezone-aware datetime for production systems. Store UTC, display local time.
Production Scope
Used for token expiry, reports, scheduling, logs, billing, deadlines, and audit trails.
More Practical Example
from datetime import datetime, timedelta, timezone
created_at = datetime.now(timezone.utc)
expires_at = created_at + timedelta(hours=24)
print(created_at.strftime("%Y-%m-%d"))
print(expires_at > created_at)Common Mistakes
- Using naive datetime in distributed systems.
- Comparing string dates instead of datetime objects.
- Ignoring timezone conversion.
Practice Task
Python RegEx
Module: re — for pattern matching in strings.
1️⃣ Basic Match
2️⃣ Common Functions
3️⃣ Special Characters
| Char | Meaning |
|---|---|
| . | Any char |
| ^ | Start |
| $ | End |
| * | 0 or more |
| + | 1 or more |
| ? | 0 or 1 |
| \d | Digit |
| \s | Whitespace |
| \w | Word char |
| [abc] | Set |
| [a-z] | Range |
🚀 Real-Time: Email Validator
🚀 Phone Validator
🔎 Extra Detailed Explanation
Beginner View
Regex searches for text patterns.
Developer View
Use raw strings, compile repeated patterns, and prefer fullmatch for complete validation.
Production Scope
Used in validation, log parsing, data extraction, cleanup, and import pipelines.
More Practical Example
import re
email = "anu@example.com"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
print(bool(re.fullmatch(pattern, email)))
text = "Order INV-2026-001 is paid"
print(re.findall(r"INV-\d{4}-\d{3}", text))Common Mistakes
- Forgetting raw string r"".
- Using regex to parse complex HTML/XML.
- Using search when fullmatch is required.
Practice Task
Python Math
1️⃣ Built-in Math Functions
2️⃣ math Module
3️⃣ random Module
🔎 Extra Detailed Explanation
Beginner View
Python Math is an important Python topic. Learn the simple definition first, then practice with small programs.
Developer View
At developer level, focus on syntax, behavior, edge cases, common methods, and how this topic appears inside real projects.
Production Scope
In production, use python math with validation, error handling, logging, tests, and clear code structure.
More Practical Example
# Practice example for Python Math
print("Learning: Python Math")Common Mistakes
- Skipping small examples before using it in a big project.
- Not testing edge cases.
- Not reading official documentation for exact behavior.
Practice Task
Python Modules
A module = a Python file (.py) with reusable code.
1️⃣ Create a Module
2️⃣ Use Module
3️⃣ Rename / Alias
4️⃣ from..import
5️⃣ List Module Functions
6️⃣ Built-in Modules
| Module | Use |
|---|---|
| os | OS operations |
| sys | System info |
| math | Math functions |
| random | Random numbers |
| datetime | Date/time |
| json | JSON handling |
| re | Regex |
| csv | CSV files |
| urllib | URL handling |
| collections | Special containers |
🔎 Extra Detailed Explanation
Beginner View
A module is a Python file that can be imported into another file.
Developer View
Organize projects into modules and packages to avoid huge files.
Production Scope
Project structure improves testing, reuse, deployment, and maintenance.
More Practical Example
# math_utils.py
def add(a, b):
return a + b
# app.py
from math_utils import add
print(add(2, 3))Common Mistakes
- Naming files json.py or random.py and shadowing standard library.
- Using import * in production.
- Creating circular imports.
Practice Task
Python PIP
PIP is a package manager for Python — install/manage external libraries.
1️⃣ Check PIP Version
2️⃣ Install a Package
3️⃣ Use Installed Package
4️⃣ Uninstall / List / Upgrade
5️⃣ Virtual Environment (venv)
📦 Popular Packages
| Package | Use |
|---|---|
| requests | HTTP requests |
| numpy | Arrays / Math |
| pandas | Data analysis |
| matplotlib | Plotting |
| flask / django | Web frameworks |
| pillow | Image processing |
| beautifulsoup4 | Web scraping |
| pytest | Testing |
🔎 Extra Detailed Explanation
Beginner View
pip installs third-party packages.
Developer View
Use python -m pip and virtual environments for reliable package management.
Production Scope
Pin dependencies and install from requirements.txt or pyproject.toml in CI/CD.
More Practical Example
python -m pip install requests python -m pip show requests python -m pip freeze > requirements.txt python -m pip install -r requirements.txt
Common Mistakes
- Installing globally.
- Forgetting to freeze dependencies.
- Not pinning production versions.
Practice Task
NumPy Basics
NumPy = Numerical Python. Used for fast array operations. Install: pip install numpy
1️⃣ Create Arrays
2️⃣ 2D Array (Matrix)
3️⃣ Special Arrays
4️⃣ Indexing & Slicing
5️⃣ Math Operations
6️⃣ Aggregations
7️⃣ Reshape
🚀 Real-Time: Student Marks
🔎 Extra Detailed Explanation
Beginner View
NumPy provides fast arrays for numerical computing.
Developer View
Understand ndarray, shape, dtype, slicing, broadcasting, vectorization, and axis.
Production Scope
Used in ML, simulations, scientific computing, and numerical pipelines.
More Practical Example
import numpy as np marks = np.array([[80, 90, 70], [75, 85, 95]]) print(marks.mean(axis=1)) print(marks[:, 1])
Common Mistakes
- Confusing axis=0 and axis=1.
- Using loops instead of vectorization.
- Ignoring dtype.
Practice Task
Pandas Basics
Pandas = Data analysis library. Install: pip install pandas
1️⃣ Series (1D)
2️⃣ DataFrame (2D)
3️⃣ Read CSV
4️⃣ Access Data
5️⃣ Filter Data
6️⃣ Add / Modify Columns
7️⃣ Sort Data
8️⃣ Group By
9️⃣ Handle Missing Data
🔟 Save to CSV
🚀 Real-Time: Sales Analysis
🔎 Extra Detailed Explanation
Beginner View
Pandas works with table-like data using DataFrame and Series.
Developer View
Learn read_csv, filtering, grouping, merging, missing data, sorting, and exporting.
Production Scope
Used in reports, data cleaning, ETL prototypes, QA checks, Excel automation, and ML preparation.
More Practical Example
import pandas as pd
sales = pd.DataFrame({"product": ["A","B","A"], "qty": [2,3,4], "price": [100,200,100]})
sales["total"] = sales["qty"] * sales["price"]
print(sales.groupby("product")["total"].sum())Common Mistakes
- Ignoring missing values.
- Using chained assignment.
- Loading huge files without chunks.
Practice Task
Matplotlib Basics
Matplotlib = Plotting library. Install: pip install matplotlib
1️⃣ Line Plot
2️⃣ Bar Chart
3️⃣ Pie Chart
4️⃣ Scatter Plot
5️⃣ Histogram
6️⃣ Multiple Lines
7️⃣ Subplots
🚀 Real-Time: Sales Dashboard
plt.savefig("chart.png") to save your chart as an image file instead of displaying it.🔎 Extra Detailed Explanation
Beginner View
Matplotlib creates charts from data.
Developer View
Use correct chart type, labels, titles, legends, grids, and savefig for reports.
Production Scope
Used in analytics reports, ML evaluation, automated dashboards, and visual summaries.
More Practical Example
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar"]
sales = [100, 150, 130]
plt.plot(months, sales, marker="o")
plt.title("Sales")
plt.savefig("sales.png")
print("saved")Common Mistakes
- No labels/title.
- Too many categories in pie chart.
- Not closing figures in loops.
Practice Task
CSV File Handling
CSV (Comma Separated Values) is the most common format for importing/exporting data from spreadsheets and databases.
1️⃣ Reading CSV
2️⃣ Reading as Dictionary
3️⃣ Writing CSV
4️⃣ Writing with DictWriter
5️⃣ CSV with Pandas (Easier)
newline="" when opening CSV files for writing on Windows to avoid extra blank lines.🔎 Extra Detailed Explanation
Beginner View
CSV stores table data as rows and columns.
Developer View
Use csv.reader for lists and csv.DictReader for dictionaries. Use newline="" when writing.
Production Scope
CSV is common for import/export, reports, migrations, spreadsheet integrations, and batch jobs.
More Practical Example
import csv
rows = [{"name": "Anu", "marks": 88}, {"name": "Ravi", "marks": 76}]
with open("students.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "marks"])
writer.writeheader()
writer.writerows(rows)
print("CSV written")Common Mistakes
- Splitting CSV manually with comma.
- Forgetting newline="".
- Not validating headers.
Practice Task
Virtual Environments
Virtual environments isolate project dependencies so different projects can use different package versions without conflicts.
1️⃣ Create a Virtual Environment
2️⃣ Using the Virtual Environment
3️⃣ Deactivate
4️⃣ Recreate from requirements.txt
5️⃣ Why Use Virtual Environments?
| Without venv | With venv |
|---|---|
| All projects share same packages | Each project has isolated packages |
| Version conflicts between projects | No conflicts — separate environments |
| Messy global Python installation | Clean, reproducible setups |
venv/ folder to Git. Add it to .gitignore.🔎 Extra Detailed Explanation
Beginner View
A virtual environment isolates packages for one project.
Developer View
Use one virtual environment per project to prevent dependency conflicts.
Production Scope
Recreate environments using requirements.txt/pyproject.toml in CI/CD and deployment.
More Practical Example
python -m venv .venv # Windows .venv\Scripts\activate # macOS/Linux source .venv/bin/activate pip install flask
Common Mistakes
- Committing .venv to Git.
- Installing packages before activation.
- Using wrong interpreter in VS Code.
Practice Task
Flask — Web Framework
Flask is a lightweight Python web framework. Install: pip install flask
1️⃣ Hello World App
2️⃣ Routes & Dynamic URLs
3️⃣ Templates (Jinja2)
my_app/
├── app.py
├── templates/
│ └── index.html
└── static/
└── style.css4️⃣ Form Handling
5️⃣ Redirects & Flash Messages
app.secret_key = "your-secret" to use sessions and flash messages.🔎 Extra Detailed Explanation
Beginner View
Flask is a lightweight framework for web apps and APIs.
Developer View
Use routes, request, jsonify, blueprints, config, validation, error handlers, and tests.
Production Scope
Run Flask with production WSGI server, logging, environment config, and security settings.
More Practical Example
from flask import Flask, jsonify
app = Flask(__name__)
@app.get("/health")
def health():
return jsonify({"status": "ok"})
if __name__ == "__main__":
app.run(debug=True)Common Mistakes
- Using debug=True in production.
- Putting all logic in app.py.
- No validation or error handlers.
Practice Task
Flask REST API
Build RESTful APIs with Flask using JSON request/response patterns.
1️⃣ Basic REST API
2️⃣ POST — Create Resource
3️⃣ PUT — Update Resource
4️⃣ DELETE — Remove Resource
5️⃣ Testing with curl
🔎 Extra Detailed Explanation
Beginner View
A REST API uses HTTP methods to work with resources.
Developer View
Use proper methods/status codes: GET 200, POST 201, validation 400, not found 404.
Production Scope
Separate routes, services, repositories, schemas, and tests.
More Practical Example
from flask import Flask, request, jsonify
app = Flask(__name__)
students = []
@app.post("/students")
def create_student():
data = request.get_json()
if not data.get("name"):
return jsonify({"error": "name required"}), 400
student = {"id": len(students)+1, "name": data["name"]}
students.append(student)
return jsonify(student), 201Common Mistakes
- Always returning 200.
- No input validation.
- Using in-memory data for production.
Practice Task
Django — Full-Stack Framework
Django is a high-level Python web framework with batteries included. Install: pip install django
1️⃣ Create a Django Project
2️⃣ Project Structure
mysite/
├── manage.py
├── mysite/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── blog/
├── models.py
├── views.py
├── urls.py
└── templates/3️⃣ Models (Database)
4️⃣ Views
5️⃣ URLs
6️⃣ Migrations
| Feature | Flask | Django |
|---|---|---|
| Type | Micro-framework | Full-stack framework |
| ORM | No (use SQLAlchemy) | Built-in |
| Admin Panel | No | Built-in |
| Best For | APIs, small apps | Large apps, CMS |
🔎 Extra Detailed Explanation
Beginner View
Django is a full-stack framework with ORM, admin, auth, templates, and migrations.
Developer View
Use apps, models, views, urls, templates, forms, admin, settings, and migrations.
Production Scope
Configure allowed hosts, static files, database, secrets, security middleware, logging, and deployment server.
More Practical Example
# models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
marks = models.IntegerField()
def __str__(self):
return self.nameCommon Mistakes
- Skipping migrations.
- Putting business logic only in views.
- Using DEBUG=True in production.
Practice Task
FastAPI — Modern API Framework
FastAPI is a modern, high-performance framework for building APIs. Install: pip install fastapi uvicorn
1️⃣ Hello World
2️⃣ Path & Query Parameters
3️⃣ Request Body with Pydantic
4️⃣ CRUD API Example
5️⃣ Auto-Generated Docs
FastAPI automatically generates interactive API docs:
| URL | Description |
|---|---|
/docs | Swagger UI (interactive) |
/redoc | ReDoc (clean documentation) |
🔎 Extra Detailed Explanation
Beginner View
FastAPI builds APIs using Python type hints and automatic validation.
Developer View
Use Pydantic models, dependency injection, response models, async endpoints, and automatic docs.
Production Scope
Use Uvicorn/Gunicorn workers, logging, validation, auth, CORS, database sessions, and tests.
More Practical Example
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Student(BaseModel):
name: str
marks: int
@app.post("/students")
def create_student(student: Student):
return {"name": student.name, "passed": student.marks >= 40}Common Mistakes
- Calling blocking code inside async endpoint.
- Not using response models.
- No validation for business rules.
Practice Task
JWT Authentication
JWT (JSON Web Tokens) enables stateless authentication for APIs. Install: pip install PyJWT
1️⃣ How JWT Works
| Step | Action |
|---|---|
| 1 | User sends login credentials |
| 2 | Server validates and creates JWT token |
| 3 | Client stores token (localStorage/cookie) |
| 4 | Client sends token in header for future requests |
| 5 | Server verifies token and responds |
2️⃣ Create a JWT Token
3️⃣ Verify a JWT Token
4️⃣ Flask + JWT (Protected Route)
os.environ["SECRET_KEY"]🔎 Extra Detailed Explanation
Beginner View
JWT is a signed token used for stateless API authentication.
Developer View
A JWT has header, payload, and signature. It should include expiry and be verified on every protected request.
Production Scope
Use HTTPS, short expiry, refresh tokens, secure storage, strong secrets, and role checks.
More Practical Example
import jwt
from datetime import datetime, timedelta, timezone
secret = "change-me"
payload = {"user_id": 1, "exp": datetime.now(timezone.utc) + timedelta(minutes=30)}
token = jwt.encode(payload, secret, algorithm="HS256")
print(jwt.decode(token, secret, algorithms=["HS256"])["user_id"])Common Mistakes
- Putting passwords in JWT payload.
- No expiry.
- Not verifying signature.
Practice Task
SQLite — Built-in Database
SQLite comes with Python — no installation needed. Perfect for small apps and prototyping.
1️⃣ Create Database & Table
2️⃣ Insert Data
3️⃣ Query Data
4️⃣ Update & Delete
5️⃣ Using Context Manager
?) to prevent SQL injection attacks.🔎 Extra Detailed Explanation
Beginner View
SQLite is a small file-based database included with Python.
Developer View
Use parameterized queries, transactions, and context managers.
Production Scope
Good for local apps and prototypes; use Postgres/MySQL for high-concurrency production web apps.
More Practical Example
import sqlite3
with sqlite3.connect("app.db") as conn:
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cur.execute("INSERT INTO users (name) VALUES (?)", ("Anu",))
cur.execute("SELECT * FROM users")
print(cur.fetchall())Common Mistakes
- String-building SQL with user input.
- Forgetting commit.
- No indexes on query fields.
Practice Task
MySQL with Python
Connect Python to MySQL databases. Install: pip install mysql-connector-python
1️⃣ Connect to MySQL
2️⃣ Create Table
3️⃣ CRUD Operations
4️⃣ Close Connection
%s placeholders (not f-strings) to prevent SQL injection.🔎 Extra Detailed Explanation
Beginner View
MySQL is a relational database server used for structured data.
Developer View
Use connectors/ORMs, parameterized queries, connection pooling, indexes, and migrations.
Production Scope
Use environment variables for credentials and managed DB services where possible.
More Practical Example
# Example pattern
sql = "SELECT * FROM users WHERE email = %s"
params = ("anu@example.com",)
# cursor.execute(sql, params)Common Mistakes
- Using f-strings in SQL with user input.
- Opening too many connections.
- No indexes on frequently filtered columns.
Practice Task
MongoDB with Python
MongoDB is a NoSQL document database. Install: pip install pymongo
1️⃣ Connect to MongoDB
2️⃣ Insert Documents
3️⃣ Query Documents
4️⃣ Update & Delete
| SQL (MySQL) | NoSQL (MongoDB) |
|---|---|
| Table | Collection |
| Row | Document |
| Column | Field |
| JOIN | Embedding / $lookup |
🔎 Extra Detailed Explanation
Beginner View
MongoDB stores flexible JSON-like documents.
Developer View
Use collections, documents, indexes, insert/find/update/delete, and schema planning.
Production Scope
Create indexes, validate data, avoid unbounded arrays, and design documents around access patterns.
More Practical Example
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
col = client.school.students
col.insert_one({"name": "Anu", "skills": ["Python"]})
print(col.find_one({"name": "Anu"})["skills"])Common Mistakes
- No indexes.
- Inconsistent document structure.
- Storing huge growing arrays in one document.
Practice Task
SQLAlchemy — Python ORM
SQLAlchemy maps Python classes to database tables. Install: pip install sqlalchemy
1️⃣ Setup & Create Engine
2️⃣ Define Models
3️⃣ CRUD Operations
4️⃣ Querying with Filters
🔎 Extra Detailed Explanation
Beginner View
SQLAlchemy maps Python classes to relational database tables.
Developer View
Understand engine, session, model, query, transaction, relationship, and migrations with Alembic.
Production Scope
Use sessions carefully, close connections, and use migrations for schema changes.
More Practical Example
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)Common Mistakes
- Not closing sessions.
- No migrations.
- Mixing query code everywhere instead of repositories/services.
Practice Task
Scikit-learn — Machine Learning
Scikit-learn provides simple ML algorithms. Install: pip install scikit-learn
1️⃣ ML Workflow
| Step | Action |
|---|---|
| 1 | Load/Prepare data |
| 2 | Split into train/test |
| 3 | Choose model |
| 4 | Train the model |
| 5 | Evaluate accuracy |
| 6 | Make predictions |
2️⃣ Linear Regression
3️⃣ Classification (Decision Tree)
4️⃣ Common Algorithms
| Algorithm | Type | Use Case |
|---|---|---|
| LinearRegression | Regression | Predict numbers |
| DecisionTree | Both | Classification/Regression |
| RandomForest | Both | Better accuracy |
| KNN | Classification | Pattern matching |
| SVM | Classification | Complex boundaries |
🔎 Extra Detailed Explanation
Beginner View
Scikit-learn trains classical machine learning models.
Developer View
Follow workflow: split data, preprocess, train, evaluate, tune, save, monitor.
Production Scope
Used for classification, regression, clustering, scoring, churn, fraud, and forecasting baselines.
More Practical Example
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score X, y = load_iris(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) model = RandomForestClassifier(random_state=42) model.fit(X_train, y_train) print(accuracy_score(y_test, model.predict(X_test)))
Common Mistakes
- Training and testing on same data.
- Data leakage during preprocessing.
- Using accuracy only for imbalanced data.
Practice Task
Requests — HTTP Library
The requests library makes HTTP calls simple. Install: pip install requests
1️⃣ GET Request
2️⃣ POST Request
3️⃣ Headers & Authentication
4️⃣ Query Parameters
5️⃣ Error Handling
6️⃣ Download a File
requests.Session() for multiple requests to the same server — it reuses connections for better performance.🔎 Extra Detailed Explanation
Beginner View
requests makes HTTP API calls simple.
Developer View
Use params, json, headers, timeout, raise_for_status, Session, and exception handling.
Production Scope
Every external API call should have timeout, logging, retry strategy, and secret-safe headers.
More Practical Example
import requests
try:
r = requests.get("https://jsonplaceholder.typicode.com/posts/1", timeout=5)
r.raise_for_status()
print(r.json()["id"])
except requests.exceptions.RequestException as e:
print("API error", e)Common Mistakes
- No timeout.
- Ignoring status codes.
- Logging auth tokens.
Practice Task
Async / Await
Asynchronous programming lets you run multiple tasks concurrently without blocking — ideal for I/O operations like API calls and file reading.
1️⃣ Basic Async Function
2️⃣ Running Multiple Tasks
3️⃣ Async HTTP Requests (aiohttp)
4️⃣ Sync vs Async Comparison
| Synchronous | Asynchronous |
|---|---|
| Tasks run one after another | Tasks run concurrently |
| Blocks while waiting | Does other work while waiting |
| Simple to write | Better performance for I/O |
| 3 API calls × 1s = 3s total | 3 API calls × 1s = ~1s total |
🔎 Extra Detailed Explanation
Beginner View
async/await lets Python wait for I/O without blocking other async tasks.
Developer View
Use async for network/database/file I/O that supports async libraries. Do not block the event loop.
Production Scope
Used for high-concurrency APIs, websocket servers, async DB calls, and parallel API integrations.
More Practical Example
import asyncio
async def task(name, delay):
await asyncio.sleep(delay)
return name
async def main():
result = await asyncio.gather(task("A", 2), task("B", 1))
print(result)
asyncio.run(main())Common Mistakes
- Forgetting await.
- Calling blocking requests inside async.
- Using async for CPU-heavy tasks.
Practice Task
Testing in Python
Testing ensures your code works correctly. Python has built-in unittest and the popular pytest library.
1️⃣ Using unittest
2️⃣ Using pytest (Recommended)
3️⃣ Testing Exceptions
4️⃣ Fixtures (Setup/Teardown)
| Assertion | Purpose |
|---|---|
assertEqual(a, b) | a == b |
assertTrue(x) | x is True |
assertIn(a, b) | a in b |
assertRaises(Error) | Function raises Error |
🔎 Extra Detailed Explanation
Beginner View
Testing verifies that your code works as expected.
Developer View
Use pytest/unittest, fixtures, parameterized tests, mocks, and CI runs.
Production Scope
Tests protect business logic, APIs, migrations, data pipelines, and bug fixes.
More Practical Example
import pytest
def divide(a, b):
if b == 0:
raise ValueError("zero")
return a / b
def test_divide():
assert divide(10, 2) == 5
def test_zero():
with pytest.raises(ValueError):
divide(1, 0)Common Mistakes
- Only testing happy path.
- Tests depend on execution order.
- Using real external services in unit tests.
Practice Task
Docker for Python
Docker packages your Python app with all dependencies into a portable container.
1️⃣ Dockerfile for Python App
2️⃣ Build & Run
3️⃣ Docker Compose (Multi-Service)
4️⃣ Common Docker Commands
| Command | Purpose |
|---|---|
docker ps | List running containers |
docker stop myapp | Stop a container |
docker logs myapp | View container logs |
docker exec -it myapp bash | Enter container shell |
docker-compose up | Start all services |
docker-compose down | Stop all services |
5️⃣ .dockerignore
🔎 Extra Detailed Explanation
Beginner View
Docker packages your Python app and dependencies into a container.
Developer View
Use Dockerfile, .dockerignore, requirements.txt, environment variables, and non-root users.
Production Scope
Containers are used in ECS, Kubernetes, CI/CD, workers, APIs, and scheduled jobs.
More Practical Example
FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["python", "app.py"]
Common Mistakes
- No .dockerignore.
- Copying secrets into image.
- Using development server in production.
Practice Task
Final Project — Student Management API
Build a complete REST API combining Flask, SQLite, JWT authentication, and testing.
1️⃣ Project Structure
student_api/ ├── app.py (main application) ├── models.py (database models) ├── auth.py (JWT authentication) ├── tests/ │ └── test_api.py ├── requirements.txt ├── Dockerfile └── .env
2️⃣ Main Application (app.py)
3️⃣ Testing (test_api.py)
4️⃣ Requirements & Run
🎯 Project Checklist
| Feature | Concepts Used |
|---|---|
| REST API endpoints | Flask routes, JSON |
| Database CRUD | SQLite, SQL queries |
| Authentication | JWT tokens, decorators |
| Testing | pytest, fixtures |
| Deployment | Docker, requirements.txt |
🔎 Extra Detailed Explanation
Beginner View
The final project combines all learned concepts into one useful backend app.
Developer View
A production-style project separates routes, services, repositories, models, schemas, tests, config, and deployment.
Production Scope
Add auth, logging, validation, database, Docker, tests, error handling, and environment variables.
More Practical Example
def calculate_grade(marks: int) -> str:
if marks >= 90:
return "A+"
if marks >= 80:
return "A"
if marks >= 70:
return "B"
return "C"
print(calculate_grade(88))Common Mistakes
- Everything in one file.
- No validation.
- Hardcoded secrets.
- No tests.
Practice Task
Input and Output
Input means taking data from the user. Output means showing data to the user. In beginner Python, we use input() and print().
Important Point
input() always returns a string. If the user types 25, Python receives it as "25", not as number 25.
Example: Safe Input
name = input("Enter name: ")
age_text = input("Enter age: ")
try:
age = int(age_text)
print(f"Hello {name}, next year you will be {age + 1}")
except ValueError:
print("Age must be a number")Production Scope
Common Mistakes
- Adding strings instead of numbers: "10" + "20" becomes "1020".
- Not catching ValueError.
- Printing secrets like passwords or API keys.
None and Missing Values
None means no value, missing value, or nothing returned. It is not the same as 0, False, or empty string.
Correct Checks
user = None
if user is None:
print("No user found")
age = 0
if age is not None:
print("Age is available")Production Scope
None when database record is not found, optional config is missing, or a function has no result. For APIs, convert None into proper response like 404 or default value.Common Mistake
if value: when 0 is a valid value. Use if value is not None:.Mutability and Copying
Mutable objects can change after creation. Lists, dictionaries, and sets are mutable. Strings, numbers, and tuples are immutable.
Reference vs Copy
a = [1, 2, 3] b = a b.append(4) print(a) print(b)
Deep Copy for Nested Data
import copy original = [[1, 2], [3, 4]] deep = copy.deepcopy(original) deep[0].append(99) print(original) print(deep)
Production Scope
All Comprehensions
Comprehensions are short syntax for creating lists, dictionaries, sets, and generators from existing iterables.
Examples
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
even_squares = [n * n for n in numbers if n % 2 == 0]
lookup = {n: n * n for n in numbers}
unique_remainders = {n % 2 for n in numbers}
total = sum(n * n for n in numbers)
print(squares)
print(even_squares)
print(lookup)
print(unique_remainders)
print(total)Common Mistake
pathlib Paths
pathlib is the modern way to work with file and folder paths. It is cleaner than joining strings manually.
from pathlib import Path
folder = Path("reports")
folder.mkdir(exist_ok=True)
file_path = folder / "summary.txt"
file_path.write_text("Report ready", encoding="utf-8")
print(file_path.exists())
print(file_path.read_text(encoding="utf-8"))Production Scope
Logging
Logging is the production replacement for print debugging. It records application events with levels.
| Level | Meaning |
|---|---|
| DEBUG | Detailed developer information |
| INFO | Normal application flow |
| WARNING | Unexpected but recoverable |
| ERROR | Operation failed |
| CRITICAL | Severe failure |
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s"
)
try:
result = 10 / 0
except ZeroDivisionError:
logging.exception("Division failed")Production Scope
Type Hints
Type hints show what type a variable, parameter, or return value should have. Python does not enforce them automatically, but tools and IDEs use them.
from typing import TypedDict
class User(TypedDict):
id: int
name: str
is_admin: bool
def greet(user: User) -> str:
return f"Hello {user['name']}"
print(greet({"id": 1, "name": "Anu", "is_admin": True}))Production Scope
argparse CLI Tools
argparse helps create command-line tools with arguments, flags, validation, and automatic help text.
import argparse
parser = argparse.ArgumentParser(description="Simple greeting CLI")
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)
args = parser.parse_args()
for _ in range(args.times):
print(f"Hello {args.name}")Production Scope
Environment Variables
Environment variables store configuration outside code: database URLs, API keys, environment names, debug flags, and secrets.
import os
APP_ENV = os.environ.get("APP_ENV", "development")
DEBUG = os.environ.get("DEBUG", "false").lower() == "true"
print(APP_ENV)
print(DEBUG)Production Scope
subprocess
subprocess lets Python run external commands safely and capture their output.
import subprocess
result = subprocess.run(
["python", "--version"],
capture_output=True,
text=True
)
print(result.returncode)
print(result.stdout or result.stderr)Production Scope
shell=True with user input because it can cause command injection vulnerabilities.Threading
Threading runs multiple tasks in the same process. It is most useful for I/O-bound tasks such as API calls, downloads, and file operations.
from concurrent.futures import ThreadPoolExecutor
import time
def work(n):
time.sleep(1)
return n * n
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(work, [1, 2, 3]))
print(results)Production Scope
Multiprocessing
Multiprocessing runs code in separate processes, allowing CPU-bound Python work to use multiple CPU cores.
from concurrent.futures import ProcessPoolExecutor
def cpu_task(n):
return sum(i * i for i in range(n))
if __name__ == "__main__":
with ProcessPoolExecutor() as executor:
results = list(executor.map(cpu_task, [10000, 20000, 30000]))
print(results)Production Scope
if __name__ == "__main__":.