← Back

Py Python Complete Tutorial

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

print("Hello, World!")
Output:Hello, World!
💡 Tip: Python uses indentation (whitespace) to define code blocks instead of curly braces { }.

🔎 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)
Output:Hello Anu, welcome to Python!

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

Create a Python file with one function, one list, one dictionary, one if/else, and one loop.

Install Python

Step 1: Check if Python is Already Installed

# Windows (CMD/PowerShell) python --version # Mac/Linux python3 --version

Step 2: Download Python

Go to 👉 https://www.python.org/downloads/ and download the latest version (3.12+).

⚠️ IMPORTANT: While installing on Windows, check ✅ "Add Python to PATH"

Step 3: Verify Installation

python --version # Output: Python 3.12.0 pip --version # Output: pip 23.x.x

Step 4: Run Python

# Method 1: Interactive Mode python >>> print("Hello") # Method 2: Run a file python myfile.py

Best IDEs for Python

IDEBest For
VS CodeAll-purpose (recommended)
PyCharmLarge projects, Django
Jupyter NotebookData Science, ML
IDLEBeginners (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
Output:Python 3.x.x pip x.x Successfully installed 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

Create a new folder, create .venv, activate it, install requests, and run a Python file.

Python Syntax

1️⃣ Execute Python Syntax

print("Hello, World!")

2️⃣ Indentation (VERY IMPORTANT)

Python uses indentation (spaces at start of line) to indicate a block of code.

# ✅ Correct if 5 > 2: print("Five is greater") # ❌ Wrong - will give IndentationError if 5 > 2: print("Five is greater")
⚠️ The number of spaces is up to you (usually 4), but it must be CONSISTENT within the same block.

3️⃣ Python Variables

x = 5 y = "Hello" print(x) print(y)

4️⃣ Case Sensitive

a = 4 A = "Sally" # A and a are TWO different variables print(a) # 4 print(A) # Sally

🔎 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")
Output:Excellent Certificate eligible 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

Write a small program with if, for, function, and class blocks using correct indentation.

Python Comments

Comments explain code, make it readable, and prevent execution while testing.

1️⃣ Single-Line Comment

# This is a comment print("Hello, World!") print("Hello") # Comment after code

2️⃣ Multi-Line Comment

# This is comment 1 # This is comment 2 # This is comment 3 print("Hello")

3️⃣ Multi-Line Strings as Comments

""" This is a multi-line string used as a comment. Python ignores it if not assigned. """ print("Hello")
💡 Use comments to: explain WHY, document functions, mark TODOs, debug code.

🔎 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))
Output:900.0

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

Add docstrings to three functions: validate_email, calculate_total, and create_user.

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

x = 5 y = "John" print(x) # 5 print(y) # John

2️⃣ Variables Can Change Type

x = 4 # int x = "Sally" # str (now changed) print(x) # Sally

3️⃣ Casting (Specify the type)

x = str(3) # '3' y = int(3) # 3 z = float(3) # 3.0 print(x, y, z)

4️⃣ Get the Type

x = 5 y = "John" print(type(x)) # <class 'int'> print(type(y)) # <class 'str'>

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.)
# ✅ Legal myvar = "John" my_var = "John" _my_var = "John" myVar2 = "John" # ❌ Illegal # 2myvar = "John" - starts with number # my-var = "John" - hyphen not allowed # my var = "John" - space not allowed

6️⃣ Multi-word Variable Naming Styles

# Camel Case myVariableName = "John" # Pascal Case MyVariableName = "John" # Snake Case (Recommended in Python) my_variable_name = "John"

7️⃣ Assign Multiple Values

# Many values to multiple variables x, y, z = "Apple", "Banana", "Cherry" print(x, y, z) # One value to multiple variables x = y = z = "Orange" print(x, y, z) # Unpack a collection fruits = ["apple", "banana", "cherry"] a, b, c = fruits print(a, b, c)

8️⃣ Output Variables

x = "Python is " y = "awesome" print(x + y) # Python is awesome print(x, y) # Python is awesome # f-string (modern way) name = "Anu" age = 22 print(f"Name: {name}, Age: {age}")

9️⃣ Global Variables

x = "awesome" # Global def myfunc(): global x x = "fantastic" # modifies global myfunc() print(f"Python is {x}") # Python is fantastic

🚀 Real-Time Example: User Profile

name = "Anu" age = 22 city = "Chennai" is_student = True gpa = 8.5 print("="*30) print(f"Name : {name}") print(f"Age : {age}") print(f"City : {city}") print(f"Student : {is_student}") print(f"GPA : {gpa}") print("="*30)
Output:============================== Name : Anu Age : 22 City : Chennai Student : True GPA : 8.5 ==============================

🔎 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)
Output:Anu ['Python', 'AWS', 'SQL']

Common Mistakes

  • Using reserved keywords as variable names.
  • Using unclear names in business code.
  • Expecting list assignment to create a deep copy.

Practice Task

Create variables for a student profile and print them using f-strings.

Python Data Types

Python has several built-in data types categorized into groups:

CategoryData Types
Textstr
Numericint, float, complex
Sequencelist, tuple, range
Mappingdict
Setset, frozenset
Booleanbool
Binarybytes, bytearray
NoneNoneType

Get Data Type

x = 5 print(type(x)) # <class 'int'>

Setting Data Types — All Examples

x = "Hello" # str x = 20 # int x = 20.5 # float x = 1j # complex x = ["a", "b", "c"] # list x = ("a", "b", "c") # tuple x = range(6) # range x = {"name": "John"} # dict x = {"a", "b", "c"} # set x = True # bool x = None # NoneType

🔎 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)
Output:str => text int => 10 float => 10.5 bool => True NoneType => None list => [1, 2] dict => {'id': 1} set => {1, 2} tuple => (1, 2)

Common Mistakes

  • Using float for money.
  • Using list when uniqueness is needed.
  • Confusing None with False or empty string.

Practice Task

Create one example for every common data type and print type(value).__name__.
Study Links:

Python Numbers

There are 3 numeric types in Python: int, float, complex.

1️⃣ int — Integer (whole number)

x = 1 y = 35656222554887711 z = -3255522 print(type(x)) # <class 'int'>

2️⃣ float — Decimal number

x = 1.10 y = 1.0 z = -35.59 # Scientific notation a = 35e3 # 35000.0 b = 12E4 # 120000.0 print(type(x)) # <class 'float'>

3️⃣ complex — Complex number

x = 3+5j y = 5j print(type(x)) # <class 'complex'>

4️⃣ Type Conversion

x = 1 y = 2.8 z = 1j a = float(x) b = int(y) c = complex(x) print(a, b, c) # 1.0 2 (1+0j)

5️⃣ Random Numbers

import random print(random.randrange(1, 10)) print(random.randint(1, 10)) print(random.random()) print(random.choice(["a","b","c"]))

🚀 Real-Time: Calculator

price = 250.75 quantity = 3 discount = 10 gst = 18 subtotal = price * quantity discount_amt = subtotal * discount / 100 after_discount = subtotal - discount_amt gst_amt = after_discount * gst / 100 total = after_discount + gst_amt print(f"Subtotal : ₹{subtotal:.2f}") print(f"Discount(10%): ₹{discount_amt:.2f}") print(f"GST(18%) : ₹{gst_amt:.2f}") print(f"Grand Total : ₹{total:.2f}")
Output:Subtotal : ₹752.25 Discount(10%): ₹75.23 GST(18%) : ₹121.87 Grand Total : ₹798.89

🔎 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)
Output:0.30000000000000004 0.3 299.97

Common Mistakes

  • Using float for financial totals.
  • Confusing / and //.
  • Using random for passwords instead of secrets.

Practice Task

Create GST bill calculator using Decimal.

Python Casting

Casting = converting a variable from one type to another.

1️⃣ int() — Convert to Integer

x = int(1) y = int(2.8) # 2 (truncates) z = int("3") print(x, y, z)

2️⃣ float() — Convert to Float

x = float(1) y = float(2.8) z = float("4.2") print(x, y, z)

3️⃣ str() — Convert to String

x = str("s1") y = str(2) z = str(3.0) print(x, y, z)

🚀 Real-Time: User Input Calculator

num1 = int(input("Enter num1: ")) num2 = int(input("Enter num2: ")) print(f"Sum = {num1 + num2}")

🔎 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))
Output:100 0 0

Common Mistakes

  • Using bool("False") expecting False; non-empty strings are True.
  • Using int("10.5") directly.
  • Not handling invalid user input.

Practice Task

Create safe_float(value, default=0.0).
Study Links:

Python Strings

1️⃣ Create String

a = "Hello" b = 'World' print(a, b)

2️⃣ Multiline String

a = """Line 1 Line 2 Line 3""" print(a)

3️⃣ Strings as Arrays

a = "Hello, World!" print(a[1]) # e print(a[0]) # H print(a[-1]) # !

4️⃣ String Slicing

b = "Hello, World!" print(b[2:5]) # llo print(b[:5]) # Hello print(b[7:]) # World! print(b[-5:-2]) # orl print(b[::-1]) # Reverse

5️⃣ String Length

a = "Hello, World!" print(len(a)) # 13

6️⃣ Check String — in / not in

txt = "The best things in life are free!" print("free" in txt) print("expensive" not in txt)

7️⃣ Concatenate Strings

a = "Hello" b = "World" c = a + " " + b print(c)

8️⃣ Format Strings — f-string (Best Way)

age = 36 name = "John" price = 59.99 print(f"My name is {name}, age {age}") print(f"Price: ${price:.2f}") print(f"Sum = {5 + 10}")

9️⃣ Escape Characters

CodeMeaning
\'Single quote
\"Double quote
\\Backslash
\nNew line
\tTab

🔟 ALL String Methods (Quick List)

MethodDescription
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

s = " Hello World! " print(s.upper()) print(s.lower()) print(s.strip()) print(s.replace("H","J")) print(s.split()) print(s.find("World")) print(s.count("l")) print(s.title()) print("-".join(["a","b","c"])) print("5".zfill(3))

🚀 Real-Time: Username Validator

def validate_username(u): u = u.strip() if len(u) < 3: return "Too short" if not u.isalnum(): return "Only letters & numbers" if not u[0].isalpha(): return "Must start with letter" return f"'{u}' is valid" print(validate_username("Anu123")) print(validate_username("99user"))

🔎 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]}")
Output:anu@example.com True ['anu', 'example.com'] Email domain: example.com

Common Mistakes

  • Forgetting strip() before validation.
  • Using + for large repeated string building; use join().
  • Thinking replace() modifies original string.

Practice Task

Create username validator: strip spaces, require 3+ characters, allow only letters/numbers.
Study Links:

Python Booleans

Booleans represent True or False.

1️⃣ Boolean Values

print(10 > 9) # True print(10 == 9) # False print(10 < 9) # False

2️⃣ bool() Function

print(bool("Hello")) # True print(bool(15)) # True print(bool("")) # False print(bool(0)) # False print(bool(None)) # False print(bool([])) # False

3️⃣ Falsy Values

  • False, None, 0, 0.0
  • "" (empty string)
  • [] (empty list)
  • {} (empty dict)
  • () (empty tuple)

🚀 Real-Time: Login Check

username = "admin" password = "1234" if username and password: print("Login successful") else: print("Fields cannot be empty")

🔎 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))
Output:'hello' True '' False 0 False 1 True [] False [1] True None False

Common Mistakes

  • Using if value when 0 is a valid value.
  • Comparing to True with == True.
  • Confusing string "False" with boolean False.

Practice Task

Validate age where 0 is valid but None and empty string are invalid.

Python Operators

1️⃣ Arithmetic Operators

OpNameExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentx ** y
//Floor Divisionx // y
x, y = 10, 3 print(x + y) # 13 print(x - y) # 7 print(x * y) # 30 print(x / y) # 3.333... print(x % y) # 1 print(x ** y) # 1000 print(x // y) # 3

2️⃣ Assignment Operators

x = 5 x += 3 # x = x + 3 → 8 x -= 2 # 6 x *= 2 # 12 x /= 4 # 3.0 x **= 2 # 9.0 print(x)

3️⃣ Comparison Operators

OpMeaning
==Equal
!=Not Equal
>Greater than
<Less than
>=Greater or equal
<=Less or equal

4️⃣ Logical Operators

x = 10 print(x > 5 and x < 20) # True print(x > 5 or x < 3) # True print(not(x > 5)) # False

5️⃣ Identity Operators (is, is not)

x = [1, 2] y = [1, 2] z = x print(x is z) # True print(x is y) # False print(x == y) # True

6️⃣ Membership Operators (in, not in)

x = ["apple", "banana"] print("apple" in x) # True print("mango" not in x) # True

7️⃣ Bitwise Operators

OpName
&AND
|OR
^XOR
~NOT
<<Left Shift
>>Right Shift

🚀 Real-Time: BMI Calculator

weight = 70 # kg height = 1.75 # m bmi = weight / (height ** 2) print(f"BMI: {bmi:.2f}") if bmi < 18.5: print("Underweight") elif bmi < 25: print("Normal") elif bmi < 30: print("Overweight") else: print("Obese")
Output:BMI: 22.86 Normal

🔎 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)
Output:True 900.0

Common Mistakes

  • Using is for value equality.
  • Using = instead of == in conditions.
  • Relying on complex precedence instead of parentheses.

Practice Task

Write eligibility logic for scholarship based on marks, income, and category.

Python Lists

Lists are ordered, changeable, and allow duplicates. Created with [ ].

1️⃣ Create a List

fruits = ["apple", "banana", "cherry"] print(fruits) print(type(fruits)) print(len(fruits))

2️⃣ Mixed Types

list1 = ["abc", 34, True, 40.5] print(list1)

3️⃣ Access Items

fruits = ["apple", "banana", "cherry", "orange", "kiwi"] print(fruits[0]) print(fruits[-1]) print(fruits[1:4]) print(fruits[:3]) print(fruits[2:])

4️⃣ Check if Exists

fruits = ["apple", "banana"] if "apple" in fruits: print("Yes, apple is present")

5️⃣ Change Items

fruits = ["apple", "banana", "cherry"] fruits[1] = "blackcurrant" print(fruits) fruits[0:2] = ["kiwi", "mango"] print(fruits)

6️⃣ Add Items

fruits = ["apple", "banana"] fruits.append("orange") fruits.insert(1, "mango") fruits.extend(["kiwi", "melon"]) print(fruits)

7️⃣ Remove Items

fruits = ["apple", "banana", "cherry"] fruits.remove("banana") # by value fruits.pop(0) # by index fruits.pop() # last item del fruits[0] # del keyword fruits.clear() # empty list print(fruits)

8️⃣ Loop Through List

fruits = ["apple", "banana", "cherry"] # Method 1: for loop for x in fruits: print(x) # Method 2: with index for i in range(len(fruits)): print(i, fruits[i]) # Method 3: enumerate for i, x in enumerate(fruits): print(i, x) # Method 4: while i = 0 while i < len(fruits): print(fruits[i]) i += 1

9️⃣ List Comprehension

fruits = ["apple", "banana", "cherry", "kiwi"] # Filter new = [x for x in fruits if "a" in x] print(new) # Squares nums = [x**2 for x in range(5)] print(nums) # [0, 1, 4, 9, 16] # With if-else result = ["even" if x%2==0 else "odd" for x in range(5)] print(result)

🔟 Sort List

nums = [3, 1, 4, 1, 5, 9, 2] nums.sort() print(nums) # [1,1,2,3,4,5,9] nums.sort(reverse=True) print(nums) # [9,5,4,3,2,1,1] nums.reverse() print(nums)

1️⃣1️⃣ Copy List

fruits = ["apple", "banana"] a = fruits.copy() b = list(fruits) c = fruits[:] print(a, b, c)

1️⃣2️⃣ Join Lists

a = ["a", "b"] b = [1, 2] c = a + b print(c) a.extend(b) print(a)

1️⃣3️⃣ All List Methods

MethodDescription
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

cart = [] cart.append("Milk") cart.append("Bread") cart.append("Eggs") print("Items in cart:") for i, item in enumerate(cart, 1): print(f"{i}. {item}") print(f"Total items: {len(cart)}") cart.remove("Bread") print(f"After remove: {cart}")
Output:Items in cart: 1. Milk 2. Bread 3. Eggs Total items: 3 After remove: ['Milk', 'Eggs']

🔎 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)
Output:1 learn Python 2 practice lists 3 build API Completed: learn Python Pending: ['practice lists', 'build API']

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

Build a shopping cart with add, remove, search, count, and clear operations.
Study Links:

Python Tuples

Tuples are ordered, unchangeable, allow duplicates. Created with ( ).

1️⃣ Create Tuple

fruits = ("apple", "banana", "cherry") print(fruits) print(type(fruits)) print(len(fruits))

2️⃣ One Item Tuple (need comma!)

a = ("apple",) # tuple b = ("apple") # NOT a tuple, just str print(type(a)) print(type(b))

3️⃣ Access Tuple Items

fruits = ("apple", "banana", "cherry", "orange") print(fruits[0]) print(fruits[-1]) print(fruits[1:3])

4️⃣ Update Tuple (Trick: convert to list)

x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x)

5️⃣ Unpacking Tuples

fruits = ("apple", "banana", "cherry") a, b, c = fruits print(a, b, c) # Use * to grab rest nums = (1, 2, 3, 4, 5) first, *middle, last = nums print(first, middle, last)

6️⃣ Loop Tuple

fruits = ("apple", "banana", "cherry") for x in fruits: print(x)

7️⃣ Join Tuples

a = ("a", "b") b = (1, 2) c = a + b print(c) # Multiply d = a * 3 print(d)

8️⃣ Tuple Methods

MethodDescription
count()Count occurrences
index()Find position

🚀 Real-Time: GPS Coordinates

location = (13.0827, 80.2707) # Chennai lat, lon = location print(f"Latitude: {lat}") print(f"Longitude: {lon}")

🔎 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__)
Output:10 30 20.0 tuple

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

Return latitude and longitude as a tuple and unpack them.
Study Links:

Python Sets

Sets are unordered, unchangeable*, no duplicates. Created with { }.

*Items can't be changed, but you can add/remove items.

1️⃣ Create Set

fruits = {"apple", "banana", "cherry"} print(fruits) print(type(fruits)) print(len(fruits))

2️⃣ Duplicates Removed Automatically

s = {"apple", "banana", "apple"} print(s) # {'apple', 'banana'}

3️⃣ Access (No Index — Use Loop)

fruits = {"apple", "banana", "cherry"} for x in fruits: print(x) print("apple" in fruits)

4️⃣ Add Items

fruits = {"apple", "banana"} fruits.add("orange") fruits.update(["mango", "kiwi"]) print(fruits)

5️⃣ Remove Items

fruits = {"apple", "banana", "cherry"} fruits.remove("banana") # error if not found fruits.discard("mango") # no error x = fruits.pop() # random item print(x, fruits) fruits.clear() del fruits

6️⃣ Set Operations (Union, Intersection, Difference)

a = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a | b) # Union: {1,2,3,4,5,6} print(a & b) # Intersection: {3,4} print(a - b) # Difference: {1,2} print(a ^ b) # Symmetric Diff: {1,2,5,6} # Or use methods print(a.union(b)) print(a.intersection(b)) print(a.difference(b)) print(a.symmetric_difference(b))

7️⃣ Subset / Superset

a = {1, 2} b = {1, 2, 3, 4} print(a.issubset(b)) # True print(b.issuperset(a)) # True print(a.isdisjoint(b)) # False

8️⃣ All Set Methods

MethodDescription
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

emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com"] unique = list(set(emails)) print(unique) print(f"Total unique: {len(unique)}")

🔎 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)
Output:Completed: {'S101', 'S103'} Missing: {'S102'} Extra: {'S104'}

Common Mistakes

  • Expecting set order.
  • Adding unhashable values like lists.
  • Using remove() when value may not exist; discard() is safer.

Practice Task

Remove duplicate emails from a list and sort the final result.
Study Links:

Python Dictionaries

Dictionaries store data as key:value pairs. Ordered, changeable, no duplicate keys. Created with { }.

1️⃣ Create Dictionary

car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(car) print(type(car)) print(len(car))

2️⃣ Access Values

car = {"brand": "Ford", "year": 1964} print(car["brand"]) print(car.get("year")) print(car.get("color", "N/A")) # default value print(car.keys()) print(car.values()) print(car.items())

3️⃣ Check if Key Exists

car = {"brand": "Ford"} if "brand" in car: print("Yes, brand is a key")

4️⃣ Change/Update Values

car = {"brand": "Ford", "year": 1964} car["year"] = 2020 car.update({"color": "red", "year": 2023}) print(car)

5️⃣ Add Items

car = {"brand": "Ford"} car["color"] = "white" print(car)

6️⃣ Remove Items

car = {"brand": "Ford", "year": 1964, "color": "red"} car.pop("year") # by key car.popitem() # last item del car["brand"] # del keyword car.clear() # empty print(car)

7️⃣ Loop Through Dictionary

car = {"brand": "Ford", "year": 2020} # Keys for key in car: print(key) # Values for v in car.values(): print(v) # Both for k, v in car.items(): print(f"{k}: {v}")

8️⃣ Copy Dictionary

car = {"brand": "Ford"} a = car.copy() b = dict(car) print(a, b)

9️⃣ Nested Dictionary

family = { "child1": {"name": "Emil", "year": 2004}, "child2": {"name": "Tobias", "year": 2007} } print(family["child1"]["name"]) for child, info in family.items(): print(child, info["name"])

🔟 Dictionary Comprehension

squares = {x: x**2 for x in range(5)} print(squares) # {0:0, 1:1, 2:4, 3:9, 4:16}

1️⃣1️⃣ All Dictionary Methods

MethodDescription
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

students = { "S101": {"name": "Anu", "marks": 85}, "S102": {"name": "Ravi", "marks": 72}, "S103": {"name": "Priya", "marks": 91} } # Add new student students["S104"] = {"name": "Kumar", "marks": 68} # Print all for id, info in students.items(): grade = "A" if info["marks"] >= 80 else "B" print(f"{id} - {info['name']}: {info['marks']} ({grade})") # Find topper topper = max(students, key=lambda x: students[x]["marks"]) print(f"Topper: {students[topper]['name']}")
Output:S101 - Anu: 85 (A) S102 - Ravi: 72 (B) S103 - Priya: 91 (A) S104 - Kumar: 68 (B) Topper: Priya

🔎 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"])
Output:Anu 88 S101 Anu S102 Ravi

Common Mistakes

  • Accessing missing keys directly when missing is expected.
  • Using mutable objects as keys.
  • Creating deeply nested dicts without structure.

Practice Task

Create product inventory dict keyed by product_id.

Python If...Else

Python supports usual logical conditions: ==, !=, <, >, <=, >=

1️⃣ if Statement

a = 33 b = 200 if b > a: print("b is greater than a")

2️⃣ elif

a = 33 b = 33 if b > a: print("b is greater") elif a == b: print("a and b are equal")

3️⃣ else

a = 200 b = 33 if b > a: print("b is greater") elif a == b: print("equal") else: print("a is greater")

4️⃣ Short Hand If

a, b = 2, 330 if a > b: print("a is greater") # Ternary print("A") if a > b else print("B") result = "A" if a > b else "B" print(result)

5️⃣ and / or / not

a, b, c = 200, 33, 500 if a > b and c > a: print("Both true") if a > b or a > c: print("At least one true") if not a > b: print("Reversed")

6️⃣ Nested If

x = 41 if x > 10: print("Above 10") if x > 20: print("And above 20!") else: print("But not above 20")

7️⃣ pass Statement

a, b = 33, 200 if b > a: pass # Empty if block (no error)

🚀 Real-Time: Grade Calculator

marks = 75 if marks >= 90: grade = "A+" elif marks >= 80: grade = "A" elif marks >= 70: grade = "B" elif marks >= 60: grade = "C" elif marks >= 50: grade = "D" else: grade = "F" print(f"Marks: {marks}, Grade: {grade}")

🔎 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)
Output:Distinction

Common Mistakes

  • Putting general conditions before specific conditions.
  • Using too many nested if blocks.
  • Forgetting final else for unexpected cases.

Practice Task

Write if/elif/else for order status: pending, paid, shipped, delivered, cancelled, unknown.
Study Links:

Python While Loop

Execute a set of statements as long as a condition is true.

1️⃣ Basic While

i = 1 while i < 6: print(i) i += 1

2️⃣ break Statement

i = 1 while i < 6: print(i) if i == 3: break i += 1 # Output: 1 2 3

3️⃣ continue Statement

i = 0 while i < 6: i += 1 if i == 3: continue print(i) # Skips 3

4️⃣ else with While

i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6")

🚀 Real-Time: Number Guessing

import random secret = random.randint(1, 10) attempts = 0 while True: guess = int(input("Guess (1-10): ")) attempts += 1 if guess == secret: print(f"Correct in {attempts} tries!") break elif guess < secret: print("Too low") else: print("Too high")

🔎 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)
Output:Trying 1 Trying 2 Success: True

Common Mistakes

  • Infinite loops without timeout.
  • Forgetting to update loop variable.
  • Using while when for is simpler.

Practice Task

Create a menu loop that runs until user chooses 0.
Study Links:

Python For Loop

Iterate over a sequence (list, tuple, dict, set, string).

1️⃣ Loop Through List

fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)

2️⃣ Loop Through String

for x in "banana": print(x)

3️⃣ break / continue

fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x) for x in fruits: if x == "banana": continue print(x)

4️⃣ range() Function

for x in range(6): # 0-5 print(x) for x in range(2, 6): # 2-5 print(x) for x in range(2, 30, 3): # 2,5,8,11... print(x)

5️⃣ else with For

for x in range(6): print(x) else: print("Finally finished!")

6️⃣ Nested For

adj = ["red", "big"] fruits = ["apple", "banana"] for a in adj: for f in fruits: print(a, f)

7️⃣ enumerate()

fruits = ["apple", "banana", "cherry"] for i, f in enumerate(fruits): print(i, f)

8️⃣ zip()

names = ["Anu", "Ravi"] ages = [22, 25] for n, a in zip(names, ages): print(f"{n} is {a}")

🚀 Real-Time: Multiplication Table

n = 5 for i in range(1, 11): print(f"{n} x {i} = {n*i}")

🔎 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)
Output:1 Anu 88 A 2 Ravi 76 B 3 Priya 91 A

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

Loop through products and print only low-stock items.
Study Links:

Python Match Case (Python 3.10+)

Like switch-case in other languages.

1️⃣ Basic Match

day = 4 match day: case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") case 4: print("Thursday") case 5: print("Friday")

2️⃣ Default Case

day = 9 match day: case 6: print("Saturday") case 7: print("Sunday") case _: print("Invalid day")

3️⃣ Combine Cases (|)

day = 4 match day: case 1 | 2 | 3 | 4 | 5: print("Weekday") case 6 | 7: print("Weekend")

4️⃣ Match with Guards (if)

month = 5 day = 4 match day: case 1 | 2 | 3 | 4 | 5 if month == 4: print("Weekday in April") case 1 | 2 | 3 | 4 | 5 if month == 5: print("Weekday in May") case _: print("Other")

🚀 Real-Time: HTTP Status

status = 404 match status: case 200: print("OK") case 301: print("Moved") case 404: print("Not Found") case 500: print("Server Error") case _: print("Unknown")

🔎 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")
Output:Delete resource

Common Mistakes

  • Using match on Python below 3.10.
  • Forgetting default case _.
  • Using match for very simple if/else.

Practice Task

Create match/case for HTTP methods GET, POST, PUT, DELETE.
Study Links:

Python Functions

A function is a reusable block of code. Defined using def keyword.

1️⃣ Create & Call Function

def my_function(): print("Hello from a function") my_function()

2️⃣ Arguments / Parameters

def greet(name): print(f"Hello {name}") greet("Anu") greet("Ravi")

3️⃣ Multiple Arguments

def full_name(first, last): print(f"{first} {last}") full_name("Anu", "Sharma")

4️⃣ Default Parameter

def country(c="India"): print(f"From {c}") country() # From India country("USA") # From USA

5️⃣ Keyword Arguments

def child(child1, child2, child3): print(f"Youngest: {child3}") child(child1="A", child2="B", child3="C")

6️⃣ *args (Arbitrary Args)

def total(*nums): print(sum(nums)) total(1, 2, 3, 4, 5) # 15

7️⃣ **kwargs (Arbitrary Keyword Args)

def info(**data): for k, v in data.items(): print(f"{k}: {v}") info(name="Anu", age=22, city="Chennai")

8️⃣ Return Values

def square(x): return x * x print(square(5)) # 25 # Multiple returns def stats(nums): return min(nums), max(nums), sum(nums) lo, hi, tot = stats([1,5,3,8]) print(lo, hi, tot)

9️⃣ Type Hints

def add(a: int, b: int) -> int: return a + b print(add(5, 3))

🚀 Real-Time: Tax Calculator

def calc_tax(salary): if salary <= 250000: return 0 elif salary <= 500000: return (salary - 250000) * 0.05 elif salary <= 1000000: return 12500 + (salary - 500000) * 0.20 else: return 112500 + (salary - 1000000) * 0.30 print(f"Tax: ₹{calc_tax(750000):.2f}")

🔎 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))
Output:A

Common Mistakes

  • Printing instead of returning when caller needs value.
  • Too many responsibilities in one function.
  • Using global variables instead of parameters.

Practice Task

Write functions validate_marks, calculate_grade, and print_report.
Study Links:

Python Lambda

A small anonymous function — one-line, no name.

Syntax

lambda arguments : expression

1️⃣ Basic Lambda

x = lambda a: a + 10 print(x(5)) # 15 y = lambda a, b: a * b print(y(5, 6)) # 30 z = lambda a, b, c: a + b + c print(z(5, 6, 2)) # 13

2️⃣ Lambda Inside Function

def multiplier(n): return lambda a: a * n double = multiplier(2) triple = multiplier(3) print(double(5)) # 10 print(triple(5)) # 15

3️⃣ Lambda with map()

nums = [1, 2, 3, 4] squares = list(map(lambda x: x**2, nums)) print(squares) # [1,4,9,16]

4️⃣ Lambda with filter()

nums = [1, 2, 3, 4, 5] even = list(filter(lambda x: x%2==0, nums)) print(even) # [2, 4]

5️⃣ Lambda with sorted()

people = [("Anu", 22), ("Ravi", 18), ("Priya", 25)] sorted_age = sorted(people, key=lambda x: x[1]) print(sorted_age)

6️⃣ Lambda with reduce()

from functools import reduce nums = [1, 2, 3, 4] total = reduce(lambda a, b: a+b, nums) print(total) # 10

🔎 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)
Output:[('Priya', 91), ('Anu', 88), ('Ravi', 76)] [2, 4]

Common Mistakes

  • Writing long lambdas.
  • Forgetting map/filter return iterators.
  • Using lambda when def is clearer.

Practice Task

Sort products by price using lambda.
Study Links:

Python Decorators

A decorator is a function that modifies another function.

1️⃣ Basic Decorator

def decorator(func): def wrapper(): print("Before function") func() print("After function") return wrapper @decorator def say_hi(): print("Hi!") say_hi()
Output:Before function Hi! After function

2️⃣ Decorator with Arguments

def log(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") result = func(*args, **kwargs) print(f"Returned: {result}") return result return wrapper @log def add(a, b): return a + b add(5, 3)

3️⃣ Real-Time: Timer Decorator

import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"Took {end-start:.4f}s") return result return wrapper @timer def slow(): time.sleep(1) print("Done") slow()

🔎 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}))
Output:Access denied User deleted

Common Mistakes

  • Not returning result from wrapper.
  • Not using functools.wraps.
  • Hiding too much business logic inside decorators.

Practice Task

Create @timer decorator that prints execution time.
Study Links:

Python Generators

Generators yield values one at a time using yield — memory efficient.

1️⃣ Basic Generator

def my_gen(): yield 1 yield 2 yield 3 for v in my_gen(): print(v)

2️⃣ Range with Generator

def count_up_to(n): i = 1 while i <= n: yield i i += 1 for x in count_up_to(5): print(x)

3️⃣ Generator Expression

squares = (x**2 for x in range(5)) for s in squares: print(s)

4️⃣ next() with Generator

def gen(): yield 1 yield 2 yield 3 g = gen() print(next(g)) # 1 print(next(g)) # 2 print(next(g)) # 3

🚀 Real-Time: Fibonacci Generator

def fib(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b for num in fib(10): print(num, end=" ") # 0 1 1 2 3 5 8 13 21 34

🔎 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)
Output:[1, 2] [3, 4] [5]

Common Mistakes

  • Trying to reuse an exhausted generator.
  • Converting huge generators to list.
  • Using yield where a simple list is clearer.

Practice Task

Write generator that yields even numbers up to n.
Study Links:

Python Recursion

A function that calls itself to solve a problem.

1️⃣ Factorial

def factorial(n): if n == 1: return 1 return n * factorial(n - 1) print(factorial(5)) # 120

2️⃣ Fibonacci

def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) for i in range(10): print(fib(i), end=" ")

3️⃣ Sum of List

def sum_list(lst): if not lst: return 0 return lst[0] + sum_list(lst[1:]) print(sum_list([1,2,3,4,5])) # 15

4️⃣ Power Function

def power(base, exp): if exp == 0: return 1 return base * power(base, exp - 1) print(power(2, 10)) # 1024
⚠️ Always have a base case to stop recursion, otherwise you'll get RecursionError.

🔎 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]]]))
Output:15

Common Mistakes

  • No base case.
  • Recursive call does not reduce problem.
  • Using recursion for simple loops unnecessarily.

Practice Task

Write recursive function to count files in nested folder-like dictionary.

Python Classes & Objects

A class is a blueprint, an object is an instance of that class.

1️⃣ Create a Class

class MyClass: x = 5 p1 = MyClass() print(p1.x) # 5

2️⃣ __init__() Constructor

class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)

3️⃣ __str__() Method

class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} ({self.age})" p1 = Person("John", 36) print(p1) # John (36)

4️⃣ Object Methods

class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, I'm {self.name}") p1 = Person("Anu", 22) p1.greet()

5️⃣ Modify / Delete Properties

p1.age = 40 del p1.age del p1

6️⃣ pass Statement

class Empty: pass

🚀 Real-Time: Bank Account

class Account: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amt): self.balance += amt print(f"Deposited ₹{amt}, New balance: ₹{self.balance}") def withdraw(self, amt): if amt > self.balance: print("Insufficient balance") else: self.balance -= amt print(f"Withdrew ₹{amt}, Balance: ₹{self.balance}") acc = Account("Anu", 5000) acc.deposit(2000) acc.withdraw(3000) acc.withdraw(10000)

🔎 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())
Output:Laptop True

Common Mistakes

  • Forgetting self.
  • Creating one giant class.
  • Using classes when a simple function would be enough.

Practice Task

Create BankAccount class with deposit and withdraw.
Study Links:

Python Inheritance

Inheritance lets a class inherit attributes/methods from another class.

1️⃣ Parent Class

class Person: def __init__(self, fname, lname): self.fname = fname self.lname = lname def printname(self): print(self.fname, self.lname) x = Person("John", "Doe") x.printname()

2️⃣ Child Class

class Student(Person): pass x = Student("Mike", "Olsen") x.printname()

3️⃣ Child __init__() with super()

class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.year = year def welcome(self): print(f"Welcome {self.fname} {self.lname}, year {self.year}") x = Student("Mike", "Olsen", 2024) x.welcome()

4️⃣ Multi-Level Inheritance

class A: def m1(self): print("A") class B(A): def m2(self): print("B") class C(B): def m3(self): print("C") c = C() c.m1() c.m2() c.m3()

5️⃣ Multiple Inheritance

class Father: def skills(self): print("Gardening") class Mother: def talents(self): print("Cooking") class Child(Father, Mother): pass c = Child() c.skills() c.talents()

🚀 Real-Time: Vehicle System

class Vehicle: def __init__(self, brand): self.brand = brand def start(self): print(f"{self.brand} starting...") class Car(Vehicle): def __init__(self, brand, model): super().__init__(brand) self.model = model def info(self): print(f"{self.brand} {self.model}") c = Car("Toyota", "Camry") c.start() c.info()

🔎 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"))
Output:Email sent: Welcome

Common Mistakes

  • Using inheritance only to share utility code.
  • Forgetting super().__init__().
  • Creating deep inheritance hierarchies.

Practice Task

Create Vehicle parent and Car/Bike child classes.
Study Links:

Python Polymorphism

"Many forms" — same method name, different behavior.

1️⃣ Function Polymorphism

print(len("Hello")) # 5 print(len([1,2,3,4])) # 4 print(len({"a": 1})) # 1

2️⃣ Class Method Polymorphism

class Cat: def sound(self): print("Meow") class Dog: def sound(self): print("Bark") class Cow: def sound(self): print("Moo") for animal in [Cat(), Dog(), Cow()]: animal.sound()

3️⃣ Method Overriding

class Animal: def sound(self): print("Generic") class Dog(Animal): def sound(self): print("Bark") # Override d = Dog() d.sound()

🚀 Real-Time: Shape Area

class Shape: def area(self): pass class Circle(Shape): def __init__(self, r): self.r = r def area(self): return 3.14 * self.r ** 2 class Square(Shape): def __init__(self, s): self.s = s def area(self): return self.s ** 2 for shape in [Circle(5), Square(4)]: print(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())
Output:PDF exported CSV exported

Common Mistakes

  • Using many isinstance checks instead of common method names.
  • Inconsistent method signatures.
  • No clear interface documentation.

Practice Task

Create EmailSender and SmsSender with send(message).
Study Links:

Python Encapsulation

Hiding data inside class — using private attributes.

1️⃣ Public, Protected, Private

class Demo: def __init__(self): self.public = "Public" self._protected = "Protected" self.__private = "Private" d = Demo() print(d.public) # OK print(d._protected) # OK but warning # print(d.__private) # ❌ Error print(d._Demo__private) # Name mangling

2️⃣ Getter / Setter

class Person: def __init__(self, age): self.__age = age def get_age(self): return self.__age def set_age(self, age): if age > 0: self.__age = age else: print("Invalid age") p = Person(25) print(p.get_age()) p.set_age(30) print(p.get_age())

3️⃣ @property Decorator

class Person: def __init__(self, age): self._age = age @property def age(self): return self._age @age.setter def age(self, val): if val > 0: self._age = val p = Person(25) print(p.age) # getter p.age = 30 # setter print(p.age)

🔎 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)
Output:100

Common Mistakes

  • Thinking _name is truly private.
  • Using getters/setters everywhere unnecessarily.
  • Putting slow API calls inside properties.

Practice Task

Create Student.marks property allowing only 0 to 100.
Study Links:

Magic / Dunder Methods

Methods with double underscores like __init__, __str__, etc.

Common Magic Methods

MethodPurpose
__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

class Point: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __str__(self): return f"({self.x}, {self.y})" p1 = Point(1, 2) p2 = Point(3, 4) print(p1 + p2) # (4, 6) print(p1 == p2) # False

__call__ Example

class Multiplier: def __init__(self, n): self.n = n def __call__(self, x): return x * self.n double = Multiplier(2) print(double(5)) # 10 — object called like function

🔎 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)
Output:1 Cart(['Book'])

Common Mistakes

  • Returning non-string from __str__.
  • Making operators do surprising things.
  • Not implementing __repr__ for debug-heavy objects.

Practice Task

Create Money class with __add__ and __str__.

Python File Handling

Use open() to work with files. Modes: r=read, w=write, a=append, x=create.

1️⃣ Read a File

f = open("demo.txt", "r") print(f.read()) f.close()

2️⃣ Read with 'with' (Recommended)

with open("demo.txt", "r") as f: print(f.read())

3️⃣ Read Line by Line

with open("demo.txt") as f: for line in f: print(line.strip())

4️⃣ Write to File

with open("demo.txt", "w") as f: f.write("Hello World!")

5️⃣ Append to File

with open("demo.txt", "a") as f: f.write("\nNew line added")

6️⃣ Delete File

import os if os.path.exists("demo.txt"): os.remove("demo.txt") else: print("File not found")

🚀 Real-Time: Log Writer

from datetime import datetime def log(msg): with open("app.log", "a") as f: ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S") f.write(f"[{ts}] {msg}\n") log("User logged in") log("Order placed")

🔎 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")
Output:Logged

Common Mistakes

  • Not closing files.
  • Forgetting encoding.
  • Overwriting files with w mode accidentally.

Practice Task

Create function read_lines(path) returning stripped non-empty lines.
Study Links:

Python JSON

1️⃣ Parse JSON (string → dict)

import json x = '{"name":"John","age":30,"city":"NYC"}' y = json.loads(x) print(y["age"])

2️⃣ Convert dict → JSON

import json x = {"name": "John", "age": 30} y = json.dumps(x) print(y)

3️⃣ Pretty Print

import json x = {"name": "John", "age": 30} print(json.dumps(x, indent=4, sort_keys=True))

4️⃣ Read/Write JSON File

import json data = {"name": "Anu", "age": 22} with open("data.json", "w") as f: json.dump(data, f, indent=4) with open("data.json") as f: info = json.load(f) print(info)

5️⃣ Conversion Table

PythonJSON
dictObject
list, tupleArray
strString
int, floatNumber
True / Falsetrue / false
Nonenull

🔎 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])
Output:{ "name": "Anu", "skills": [ "Python", "AWS" ], "active": true } Python

Common Mistakes

  • Using eval to parse JSON.
  • Trying to dump datetime directly.
  • Forgetting JSON requires double quotes.

Practice Task

Read config.json, update one value, and save it.
Study Links:

Python Try...Except

1️⃣ Basic Try-Except

try: print(x) except: print("Variable not defined")

2️⃣ Multiple Except Blocks

try: print(x) except NameError: print("Variable x not defined") except: print("Other error")

3️⃣ else Block

try: print("Hello") except: print("Error") else: print("No errors")

4️⃣ finally Block

try: f = open("demo.txt") except: print("Error") finally: print("Cleanup done")

5️⃣ Raise an Exception

x = -1 if x < 0: raise Exception("No negative numbers")

6️⃣ Common Exception Types

ExceptionWhen
NameErrorVariable not defined
TypeErrorWrong type used
ValueErrorRight type, wrong value
IndexErrorList index out of range
KeyErrorDict key not found
ZeroDivisionErrorDivision by 0
FileNotFoundErrorFile not found

🚀 Real-Time: Safe Division

def safe_divide(a, b): try: return a / b except ZeroDivisionError: return "Cannot divide by zero" except TypeError: return "Numbers only" print(safe_divide(10, 2)) print(safe_divide(10, 0))

🔎 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))
Output:divide attempted 5.0 divide attempted Cannot divide by zero

Common Mistakes

  • Bare except hiding real bugs.
  • Silently ignoring errors.
  • Returning confusing mixed types without documentation.

Practice Task

Create safe_file_read(path) handling FileNotFoundError.

Python Dates

1️⃣ Current Date & Time

import datetime x = datetime.datetime.now() print(x) print(x.year) print(x.strftime("%A"))

2️⃣ Create Date

import datetime x = datetime.datetime(2024, 5, 17) print(x)

3️⃣ Format Dates

import datetime x = datetime.datetime.now() print(x.strftime("%Y-%m-%d")) print(x.strftime("%d/%m/%Y")) print(x.strftime("%H:%M:%S")) print(x.strftime("%B %d, %Y"))

4️⃣ Format Codes

CodeMeaning
%YYear (2024)
%mMonth (01-12)
%BMonth name
%dDay (01-31)
%AWeekday name
%HHour 24
%MMinute
%SSecond
%pAM/PM

5️⃣ Date Arithmetic

from datetime import datetime, timedelta today = datetime.now() tomorrow = today + timedelta(days=1) last_week = today - timedelta(weeks=1) print(tomorrow) print(last_week)

🚀 Real-Time: Age Calculator

from datetime import datetime dob = datetime(2000, 5, 15) today = datetime.now() age = today.year - dob.year if (today.month, today.day) < (dob.month, dob.day): age -= 1 print(f"Age: {age}")

🔎 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)
Output:2026-05-28 True

Common Mistakes

  • Using naive datetime in distributed systems.
  • Comparing string dates instead of datetime objects.
  • Ignoring timezone conversion.

Practice Task

Create function is_expired(expires_at).
Study Links:

Python RegEx

Module: re — for pattern matching in strings.

1️⃣ Basic Match

import re txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) if x: print("Match!")

2️⃣ Common Functions

import re txt = "The rain in Spain" print(re.findall("ai", txt)) print(re.search("\s", txt).start()) print(re.split("\s", txt)) print(re.sub("\s", "-", txt))

3️⃣ Special Characters

CharMeaning
.Any char
^Start
$End
*0 or more
+1 or more
?0 or 1
\dDigit
\sWhitespace
\wWord char
[abc]Set
[a-z]Range

🚀 Real-Time: Email Validator

import re def is_email(email): pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$" return bool(re.match(pattern, email)) print(is_email("anu@gmail.com")) print(is_email("invalid.email"))

🚀 Phone Validator

import re def is_phone(p): return bool(re.match(r"^[6-9]\d{9}$", p)) print(is_phone("9876543210")) print(is_phone("123"))

🔎 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))
Output:True ['INV-2026-001']

Common Mistakes

  • Forgetting raw string r"".
  • Using regex to parse complex HTML/XML.
  • Using search when fullmatch is required.

Practice Task

Validate Indian mobile number with regex.
Study Links:

Python Math

1️⃣ Built-in Math Functions

print(min(5, 10, 25)) print(max(5, 10, 25)) print(abs(-7.25)) print(pow(4, 3)) print(round(3.14159, 2)) print(sum([1, 2, 3]))

2️⃣ math Module

import math print(math.sqrt(64)) print(math.ceil(1.4)) print(math.floor(1.4)) print(math.pi) print(math.e) print(math.factorial(5)) print(math.log(100, 10)) print(math.sin(math.pi/2))

3️⃣ random Module

import random print(random.random()) print(random.randint(1, 10)) print(random.choice(["a","b","c"])) print(random.sample([1,2,3,4], 2)) random.shuffle([1,2,3])

🔎 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")
Output: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

Create 3 mini examples for Python Math: beginner, intermediate, and real-world.

Python Modules

A module = a Python file (.py) with reusable code.

1️⃣ Create a Module

# File: mymodule.py def greeting(name): print(f"Hello {name}") person = {"name": "John", "age": 36}

2️⃣ Use Module

import mymodule mymodule.greeting("Anu") print(mymodule.person["name"])

3️⃣ Rename / Alias

import mymodule as mx print(mx.person["age"])

4️⃣ from..import

from mymodule import person print(person["name"])

5️⃣ List Module Functions

import platform print(platform.system()) print(dir(platform)) # All functions

6️⃣ Built-in Modules

ModuleUse
osOS operations
sysSystem info
mathMath functions
randomRandom numbers
datetimeDate/time
jsonJSON handling
reRegex
csvCSV files
urllibURL handling
collectionsSpecial 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))
Output:5

Common Mistakes

  • Naming files json.py or random.py and shadowing standard library.
  • Using import * in production.
  • Creating circular imports.

Practice Task

Create utils.py and import it from app.py.
Study Links:

Python PIP

PIP is a package manager for Python — install/manage external libraries.

1️⃣ Check PIP Version

# In terminal pip --version

2️⃣ Install a Package

pip install requests pip install numpy pip install pandas

3️⃣ Use Installed Package

import requests r = requests.get("https://api.github.com") print(r.status_code)

4️⃣ Uninstall / List / Upgrade

pip uninstall requests pip list pip show requests pip install --upgrade requests pip freeze > requirements.txt pip install -r requirements.txt

5️⃣ Virtual Environment (venv)

# Create python -m venv myenv # Activate (Windows) myenv\Scripts\activate # Activate (Mac/Linux) source myenv/bin/activate # Deactivate deactivate
💡 Always use virtual environments for projects to keep dependencies isolated!

📦 Popular Packages

PackageUse
requestsHTTP requests
numpyArrays / Math
pandasData analysis
matplotlibPlotting
flask / djangoWeb frameworks
pillowImage processing
beautifulsoup4Web scraping
pytestTesting

🔎 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
Output:Package installed and dependency file generated

Common Mistakes

  • Installing globally.
  • Forgetting to freeze dependencies.
  • Not pinning production versions.

Practice Task

Install requests and create requirements.txt.
Study Links:

NumPy Basics

NumPy = Numerical Python. Used for fast array operations. Install: pip install numpy

1️⃣ Create Arrays

import numpy as np a = np.array([1, 2, 3, 4, 5]) print(a) print(type(a)) print(a.shape) print(a.dtype)

2️⃣ 2D Array (Matrix)

import numpy as np b = np.array([[1,2,3], [4,5,6]]) print(b) print(b.shape) print(b.ndim)

3️⃣ Special Arrays

import numpy as np print(np.zeros((2,3))) print(np.ones((2,3))) print(np.arange(0, 10, 2)) print(np.linspace(0, 1, 5)) print(np.eye(3))

4️⃣ Indexing & Slicing

import numpy as np a = np.array([1, 2, 3, 4, 5]) print(a[0]) print(a[-1]) print(a[1:4]) b = np.array([[1,2,3], [4,5,6]]) print(b[0, 1]) print(b[:, 1]) print(b[0, :])

5️⃣ Math Operations

import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) print(a + b) print(a * 2) print(a * b) print(np.dot(a, b)) print(np.sqrt(a))

6️⃣ Aggregations

import numpy as np a = np.array([1, 2, 3, 4, 5]) print(a.sum()) print(a.mean()) print(a.min(), a.max()) print(a.std())

7️⃣ Reshape

import numpy as np a = np.arange(12) b = a.reshape(3, 4) print(b) print(b.flatten())

🚀 Real-Time: Student Marks

import numpy as np marks = np.array([[85,90,78], [72,88,95]]) print(f"Avg per student: {marks.mean(axis=1)}") print(f"Avg per subject: {marks.mean(axis=0)}") print(f"Highest: {marks.max()}")

🔎 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])
Output:[80. 85.] [90 85]

Common Mistakes

  • Confusing axis=0 and axis=1.
  • Using loops instead of vectorization.
  • Ignoring dtype.

Practice Task

Create 3x4 matrix and calculate row sums and column averages.
Study Links:

Pandas Basics

Pandas = Data analysis library. Install: pip install pandas

1️⃣ Series (1D)

import pandas as pd s = pd.Series([1, 3, 5, 7]) print(s) s = pd.Series([100, 200, 300], index=["a","b","c"]) print(s["a"])

2️⃣ DataFrame (2D)

import pandas as pd data = { "name": ["Anu", "Ravi", "Priya"], "age": [22, 25, 28], "city": ["Chennai", "Mumbai", "Delhi"] } df = pd.DataFrame(data) print(df)

3️⃣ Read CSV

import pandas as pd df = pd.read_csv("data.csv") print(df.head()) print(df.tail()) print(df.info()) print(df.describe())

4️⃣ Access Data

print(df["name"]) print(df[["name", "age"]]) print(df.iloc[0]) print(df.loc[0, "name"])

5️⃣ Filter Data

# Age > 23 print(df[df["age"] > 23]) # Multiple conditions print(df[(df["age"] > 20) & (df["city"] == "Chennai")])

6️⃣ Add / Modify Columns

df["salary"] = [50000, 60000, 70000] df["bonus"] = df["salary"] * 0.1 print(df)

7️⃣ Sort Data

df_sorted = df.sort_values("age") print(df_sorted) df_sorted = df.sort_values("age", ascending=False) print(df_sorted)

8️⃣ Group By

df = pd.DataFrame({ "dept": ["IT", "HR", "IT", "HR"], "salary": [50000, 40000, 60000, 45000] }) print(df.groupby("dept")["salary"].mean()) print(df.groupby("dept")["salary"].sum())

9️⃣ Handle Missing Data

print(df.isnull().sum()) df.dropna(inplace=True) df.fillna(0, inplace=True)

🔟 Save to CSV

df.to_csv("output.csv", index=False) df.to_excel("output.xlsx", index=False) df.to_json("output.json")

🚀 Real-Time: Sales Analysis

import pandas as pd sales = pd.DataFrame({ "product": ["A", "B", "A", "C", "B"], "qty": [10, 5, 8, 12, 3], "price": [100, 200, 100, 150, 200] }) sales["total"] = sales["qty"] * sales["price"] print(sales) print("\nProduct-wise total:") print(sales.groupby("product")["total"].sum())

🔎 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())
Output:product A 600 B 600 Name: total, dtype: int64

Common Mistakes

  • Ignoring missing values.
  • Using chained assignment.
  • Loading huge files without chunks.

Practice Task

Read CSV, clean missing values, group by category, export summary.
Study Links:

Matplotlib Basics

Matplotlib = Plotting library. Install: pip install matplotlib

1️⃣ Line Plot

import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) plt.title("Line Graph") plt.xlabel("X Axis") plt.ylabel("Y Axis") plt.show()

2️⃣ Bar Chart

import matplotlib.pyplot as plt names = ["A", "B", "C", "D"] values = [25, 40, 30, 55] plt.bar(names, values, color="skyblue") plt.title("Bar Chart") plt.show()

3️⃣ Pie Chart

import matplotlib.pyplot as plt labels = ["Apples", "Bananas", "Cherries"] sizes = [40, 30, 30] plt.pie(sizes, labels=labels, autopct="%1.1f%%") plt.title("Fruit Distribution") plt.show()

4️⃣ Scatter Plot

import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [5, 7, 3, 8, 4] plt.scatter(x, y, color="red") plt.title("Scatter Plot") plt.show()

5️⃣ Histogram

import matplotlib.pyplot as plt data = [1,2,2,3,3,3,4,4,5] plt.hist(data, bins=5, color="green") plt.title("Histogram") plt.show()

6️⃣ Multiple Lines

import matplotlib.pyplot as plt x = [1, 2, 3, 4] y1 = [2, 4, 6, 8] y2 = [1, 3, 5, 7] plt.plot(x, y1, label="Line 1") plt.plot(x, y2, label="Line 2") plt.legend() plt.grid(True) plt.show()

7️⃣ Subplots

import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 2, figsize=(10,4)) ax[0].plot([1,2,3], [4,5,6]) ax[0].set_title("Plot 1") ax[1].bar(["A","B"], [10,20]) ax[1].set_title("Plot 2") plt.show()

🚀 Real-Time: Sales Dashboard

import matplotlib.pyplot as plt months = ["Jan","Feb","Mar","Apr","May"] sales = [15000, 22000, 18000, 28000, 35000] plt.figure(figsize=(10, 5)) plt.plot(months, sales, marker="o", color="blue", linewidth=2) plt.title("Monthly Sales 2024") plt.xlabel("Month") plt.ylabel("Sales (₹)") plt.grid(True) plt.show()
💡 Tip: Use 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")
Output:saved

Common Mistakes

  • No labels/title.
  • Too many categories in pie chart.
  • Not closing figures in loops.

Practice Task

Create bar chart for product revenue.
Study Links:

CSV File Handling

CSV (Comma Separated Values) is the most common format for importing/exporting data from spreadsheets and databases.

1️⃣ Reading CSV

import csv with open("students.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)
Output:['Name', 'Age', 'Grade'] ['Anu', '22', 'A'] ['Ravi', '21', 'B+']

2️⃣ Reading as Dictionary

import csv with open("students.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(row["Name"], row["Grade"])

3️⃣ Writing CSV

import csv data = [["Name", "Age"], ["Anu", 22], ["Ravi", 21]] with open("output.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerows(data)

4️⃣ Writing with DictWriter

import csv fields = ["name", "age", "city"] rows = [ {"name": "Anu", "age": 22, "city": "Chennai"}, {"name": "Ravi", "age": 21, "city": "Hyderabad"} ] with open("people.csv", "w", newline="") as file: writer = csv.DictWriter(file, fieldnames=fields) writer.writeheader() writer.writerows(rows)

5️⃣ CSV with Pandas (Easier)

import pandas as pd # Read CSV df = pd.read_csv("students.csv") print(df) # Write CSV df.to_csv("new_file.csv", index=False)
💡 Always use 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")
Output:CSV written

Common Mistakes

  • Splitting CSV manually with comma.
  • Forgetting newline="".
  • Not validating headers.

Practice Task

Create a CSV average marks calculator.
Study Links:

Virtual Environments

Virtual environments isolate project dependencies so different projects can use different package versions without conflicts.

1️⃣ Create a Virtual Environment

# Create venv python -m venv myenv # Windows - Activate myenv\Scripts\activate # Mac/Linux - Activate source myenv/bin/activate

2️⃣ Using the Virtual Environment

# Install packages (only inside this venv) pip install flask requests pandas # See installed packages pip list # Freeze requirements pip freeze > requirements.txt

3️⃣ Deactivate

# Leave the virtual environment deactivate

4️⃣ Recreate from requirements.txt

# On a new machine or fresh venv: python -m venv newenv source newenv/bin/activate # or newenv\Scripts\activate on Windows pip install -r requirements.txt

5️⃣ Why Use Virtual Environments?

Without venvWith venv
All projects share same packagesEach project has isolated packages
Version conflicts between projectsNo conflicts — separate environments
Messy global Python installationClean, reproducible setups
⚠️ Never commit the 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
Output:Virtual environment activated and Flask installed

Common Mistakes

  • Committing .venv to Git.
  • Installing packages before activation.
  • Using wrong interpreter in VS Code.

Practice Task

Create venv, install flask, run pip freeze.

Flask — Web Framework

Flask is a lightweight Python web framework. Install: pip install flask

1️⃣ Hello World App

from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, World!" if __name__ == "__main__": app.run(debug=True)
Run:python app.py * Running on http://127.0.0.1:5000

2️⃣ Routes & Dynamic URLs

@app.route("/hello/<name>") def hello(name): return f"Hello, {name}!" @app.route("/user/<int:user_id>") def user_profile(user_id): return f"User ID: {user_id}"

3️⃣ Templates (Jinja2)

from flask import Flask, render_template @app.route("/") def home(): return render_template("index.html", name="Anu")
Folder Structure:
my_app/
├── app.py
├── templates/
│   └── index.html
└── static/
    └── style.css

4️⃣ Form Handling

from flask import Flask, request @app.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": username = request.form["username"] return f"Welcome, {username}!" return '''<form method="POST"> <input name="username"> <button>Login</button> </form>'''

5️⃣ Redirects & Flash Messages

from flask import redirect, url_for, flash @app.route("/dashboard") def dashboard(): flash("Login successful!") return redirect(url_for("home"))
💡 Set 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)
Output:GET /health -> {"status":"ok"}

Common Mistakes

  • Using debug=True in production.
  • Putting all logic in app.py.
  • No validation or error handlers.

Practice Task

Create Flask API with /students GET and POST.
Study Links:

Flask REST API

Build RESTful APIs with Flask using JSON request/response patterns.

1️⃣ Basic REST API

from flask import Flask, jsonify, request app = Flask(__name__) students = [ {"id": 1, "name": "Anu", "grade": "A"}, {"id": 2, "name": "Ravi", "grade": "B+"} ] # GET all students @app.route("/api/students", methods=["GET"]) def get_students(): return jsonify(students) # GET single student @app.route("/api/students/<int:sid>", methods=["GET"]) def get_student(sid): student = next((s for s in students if s["id"] == sid), None) if student: return jsonify(student) return jsonify({"error": "Not found"}), 404

2️⃣ POST — Create Resource

@app.route("/api/students", methods=["POST"]) def add_student(): data = request.get_json() new_student = { "id": len(students) + 1, "name": data["name"], "grade": data["grade"] } students.append(new_student) return jsonify(new_student), 201

3️⃣ PUT — Update Resource

@app.route("/api/students/<int:sid>", methods=["PUT"]) def update_student(sid): data = request.get_json() student = next((s for s in students if s["id"] == sid), None) if student: student["name"] = data.get("name", student["name"]) student["grade"] = data.get("grade", student["grade"]) return jsonify(student) return jsonify({"error": "Not found"}), 404

4️⃣ DELETE — Remove Resource

@app.route("/api/students/<int:sid>", methods=["DELETE"]) def delete_student(sid): global students students = [s for s in students if s["id"] != sid] return jsonify({"message": "Deleted"})

5️⃣ Testing with curl

# GET curl http://localhost:5000/api/students # POST curl -X POST -H "Content-Type: application/json" \ -d '{"name":"Priya","grade":"A+"}' \ http://localhost:5000/api/students
📝 For production APIs, use Flask-RESTful or Flask-RESTX for better structure and Swagger docs.

🔎 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), 201
Output:POST /students {"name":"Anu"} -> 201

Common Mistakes

  • Always returning 200.
  • No input validation.
  • Using in-memory data for production.

Practice Task

Implement GET by ID, PUT, DELETE.
Study Links:

Django — Full-Stack Framework

Django is a high-level Python web framework with batteries included. Install: pip install django

1️⃣ Create a Django Project

# Create project django-admin startproject mysite # Create app cd mysite python manage.py startapp blog # Run server python manage.py runserver

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)

# blog/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title

4️⃣ Views

# blog/views.py from django.shortcuts import render from .models import Post def post_list(request): posts = Post.objects.all().order_by("-created_at") return render(request, "blog/post_list.html", {"posts": posts})

5️⃣ URLs

# blog/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.post_list, name="post_list"), ]

6️⃣ Migrations

# Create migration files python manage.py makemigrations # Apply migrations to database python manage.py migrate # Create admin superuser python manage.py createsuperuser
FeatureFlaskDjango
TypeMicro-frameworkFull-stack framework
ORMNo (use SQLAlchemy)Built-in
Admin PanelNoBuilt-in
Best ForAPIs, small appsLarge 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.name
Output:Run makemigrations and migrate to create database table

Common Mistakes

  • Skipping migrations.
  • Putting business logic only in views.
  • Using DEBUG=True in production.

Practice Task

Create Student model and register it in Django admin.
Study Links:

FastAPI — Modern API Framework

FastAPI is a modern, high-performance framework for building APIs. Install: pip install fastapi uvicorn

1️⃣ Hello World

from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return {"message": "Hello, World!"}
Run:uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000

2️⃣ Path & Query Parameters

@app.get("/users/{user_id}") def get_user(user_id: int): return {"user_id": user_id} @app.get("/items") def get_items(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}

3️⃣ Request Body with Pydantic

from pydantic import BaseModel class Student(BaseModel): name: str age: int grade: str @app.post("/students") def create_student(student: Student): return {"message": f"Created {student.name}", "data": student}

4️⃣ CRUD API Example

from fastapi import FastAPI, HTTPException app = FastAPI() db = [] @app.post("/items") def create(item: dict): db.append(item) return item @app.get("/items") def read_all(): return db @app.get("/items/{idx}") def read_one(idx: int): if idx >= len(db): raise HTTPException(status_code=404, detail="Not found") return db[idx]

5️⃣ Auto-Generated Docs

FastAPI automatically generates interactive API docs:

URLDescription
/docsSwagger UI (interactive)
/redocReDoc (clean documentation)
💡 FastAPI is 3-5x faster than Flask due to async support and is ideal for modern APIs.

🔎 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}
Output:POST /students validates body automatically

Common Mistakes

  • Calling blocking code inside async endpoint.
  • Not using response models.
  • No validation for business rules.

Practice Task

Create FastAPI CRUD for products.
Study Links:

JWT Authentication

JWT (JSON Web Tokens) enables stateless authentication for APIs. Install: pip install PyJWT

1️⃣ How JWT Works

StepAction
1User sends login credentials
2Server validates and creates JWT token
3Client stores token (localStorage/cookie)
4Client sends token in header for future requests
5Server verifies token and responds

2️⃣ Create a JWT Token

import jwt import datetime SECRET_KEY = "my-secret-key" def create_token(user_id): payload = { "user_id": user_id, "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=24) } token = jwt.encode(payload, SECRET_KEY, algorithm="HS256") return token token = create_token(123) print(token)

3️⃣ Verify a JWT Token

def verify_token(token): try: payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) return payload except jwt.ExpiredSignatureError: return "Token expired" except jwt.InvalidTokenError: return "Invalid token" result = verify_token(token) print(result) # {'user_id': 123, 'exp': ...}

4️⃣ Flask + JWT (Protected Route)

from flask import Flask, request, jsonify from functools import wraps import jwt app = Flask(__name__) SECRET = "secret123" def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.headers.get("Authorization") if not token: return jsonify({"error": "Token missing"}), 401 try: data = jwt.decode(token, SECRET, algorithms=["HS256"]) except: return jsonify({"error": "Invalid token"}), 401 return f(data, *args, **kwargs) return decorated @app.route("/protected") @token_required def protected(user_data): return jsonify({"message": "Access granted", "user": user_data})
⚠️ Never hardcode secrets in code. Use environment variables: 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"])
Output:1

Common Mistakes

  • Putting passwords in JWT payload.
  • No expiry.
  • Not verifying signature.

Practice Task

Create login and protected route using JWT.
Study Links:

SQLite — Built-in Database

SQLite comes with Python — no installation needed. Perfect for small apps and prototyping.

1️⃣ Create Database & Table

import sqlite3 conn = sqlite3.connect("school.db") cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, grade TEXT ) """) conn.commit()

2️⃣ Insert Data

# Single insert cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", ("Anu", 22, "A")) # Multiple inserts students = [("Ravi", 21, "B+"), ("Priya", 23, "A+")] cursor.executemany("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", students) conn.commit()

3️⃣ Query Data

# Fetch all cursor.execute("SELECT * FROM students") rows = cursor.fetchall() for row in rows: print(row) # Fetch one cursor.execute("SELECT * FROM students WHERE name=?", ("Anu",)) print(cursor.fetchone())

4️⃣ Update & Delete

# Update cursor.execute("UPDATE students SET grade=? WHERE name=?", ("A+", "Anu")) # Delete cursor.execute("DELETE FROM students WHERE name=?", ("Ravi",)) conn.commit()

5️⃣ Using Context Manager

import sqlite3 with sqlite3.connect("school.db") as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM students") for row in cursor.fetchall(): print(row)
📝 Always use parameterized queries (?) 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())
Output:[(1, 'Anu')]

Common Mistakes

  • String-building SQL with user input.
  • Forgetting commit.
  • No indexes on query fields.

Practice Task

Create products table with CRUD operations.
Study Links:

MySQL with Python

Connect Python to MySQL databases. Install: pip install mysql-connector-python

1️⃣ Connect to MySQL

import mysql.connector conn = mysql.connector.connect( host="localhost", user="root", password="password", database="school_db" ) cursor = conn.cursor() print("Connected!")

2️⃣ Create Table

cursor.execute(""" CREATE TABLE IF NOT EXISTS students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100), grade VARCHAR(5) ) """) conn.commit()

3️⃣ CRUD Operations

# INSERT sql = "INSERT INTO students (name, email, grade) VALUES (%s, %s, %s)" cursor.execute(sql, ("Anu", "anu@email.com", "A")) conn.commit() # SELECT cursor.execute("SELECT * FROM students") for row in cursor.fetchall(): print(row) # UPDATE cursor.execute("UPDATE students SET grade=%s WHERE name=%s", ("A+", "Anu")) conn.commit() # DELETE cursor.execute("DELETE FROM students WHERE name=%s", ("Anu",)) conn.commit()

4️⃣ Close Connection

cursor.close() conn.close()
⚠️ Use %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)
Output:Parameterized query prevents SQL injection

Common Mistakes

  • Using f-strings in SQL with user input.
  • Opening too many connections.
  • No indexes on frequently filtered columns.

Practice Task

Create users table and query by email using parameters.

MongoDB with Python

MongoDB is a NoSQL document database. Install: pip install pymongo

1️⃣ Connect to MongoDB

from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017/") db = client["school"] collection = db["students"] print("Connected to MongoDB!")

2️⃣ Insert Documents

# Insert one student = {"name": "Anu", "age": 22, "grade": "A"} result = collection.insert_one(student) print(f"Inserted ID: {result.inserted_id}") # Insert many students = [ {"name": "Ravi", "age": 21, "grade": "B+"}, {"name": "Priya", "age": 23, "grade": "A+"} ] collection.insert_many(students)

3️⃣ Query Documents

# Find all for doc in collection.find(): print(doc) # Find with filter result = collection.find_one({"name": "Anu"}) print(result) # Find with condition for doc in collection.find({"age": {"$gt": 21}}): print(doc["name"])

4️⃣ Update & Delete

# Update one collection.update_one({"name": "Anu"}, {"$set": {"grade": "A+"}}) # Delete one collection.delete_one({"name": "Ravi"}) # Delete many collection.delete_many({"age": {"$lt": 20}})
SQL (MySQL)NoSQL (MongoDB)
TableCollection
RowDocument
ColumnField
JOINEmbedding / $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"])
Output:['Python']

Common Mistakes

  • No indexes.
  • Inconsistent document structure.
  • Storing huge growing arrays in one document.

Practice Task

Create projects collection and query by technology.
Study Links:

SQLAlchemy — Python ORM

SQLAlchemy maps Python classes to database tables. Install: pip install sqlalchemy

1️⃣ Setup & Create Engine

from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import declarative_base, sessionmaker engine = create_engine("sqlite:///school.db", echo=True) Base = declarative_base() Session = sessionmaker(bind=engine)

2️⃣ Define Models

class Student(Base): __tablename__ = "students" id = Column(Integer, primary_key=True) name = Column(String(100), nullable=False) age = Column(Integer) grade = Column(String(5)) def __repr__(self): return f"Student('{self.name}', {self.age}, '{self.grade}')" # Create tables Base.metadata.create_all(engine)

3️⃣ CRUD Operations

session = Session() # Create new_student = Student(name="Anu", age=22, grade="A") session.add(new_student) session.commit() # Read students = session.query(Student).all() for s in students: print(s) # Update student = session.query(Student).filter_by(name="Anu").first() student.grade = "A+" session.commit() # Delete session.delete(student) session.commit()

4️⃣ Querying with Filters

# Filter results = session.query(Student).filter(Student.age > 20).all() # Order by results = session.query(Student).order_by(Student.name).all() # Count count = session.query(Student).count()
💡 SQLAlchemy supports MySQL, PostgreSQL, SQLite, and Oracle — just change the connection string.

🔎 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)
Output:Defines a users table model

Common Mistakes

  • Not closing sessions.
  • No migrations.
  • Mixing query code everywhere instead of repositories/services.

Practice Task

Create Product model with SQLAlchemy.
Study Links:

Scikit-learn — Machine Learning

Scikit-learn provides simple ML algorithms. Install: pip install scikit-learn

1️⃣ ML Workflow

StepAction
1Load/Prepare data
2Split into train/test
3Choose model
4Train the model
5Evaluate accuracy
6Make predictions

2️⃣ Linear Regression

from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import numpy as np # Data: hours studied vs marks X = np.array([[1],[2],[3],[4],[5],[6],[7],[8]]) y = np.array([20,35,50,55,65,70,80,90]) # Split data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # Train model = LinearRegression() model.fit(X_train, y_train) # Predict prediction = model.predict([[9]]) print(f"9 hours study = {prediction[0]:.0f} marks") # Accuracy score = model.score(X_test, y_test) print(f"R² Score: {score:.2f}")

3️⃣ Classification (Decision Tree)

from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # Load dataset iris = load_iris() X_train, X_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.3) # Train clf = DecisionTreeClassifier() clf.fit(X_train, y_train) # Predict & evaluate predictions = clf.predict(X_test) accuracy = accuracy_score(y_test, predictions) print(f"Accuracy: {accuracy * 100:.1f}%")

4️⃣ Common Algorithms

AlgorithmTypeUse Case
LinearRegressionRegressionPredict numbers
DecisionTreeBothClassification/Regression
RandomForestBothBetter accuracy
KNNClassificationPattern matching
SVMClassificationComplex boundaries
💡 Always split data into train/test sets to avoid overfitting.

🔎 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)))
Output:1.0

Common Mistakes

  • Training and testing on same data.
  • Data leakage during preprocessing.
  • Using accuracy only for imbalanced data.

Practice Task

Train model and print classification_report.

Requests — HTTP Library

The requests library makes HTTP calls simple. Install: pip install requests

1️⃣ GET Request

import requests response = requests.get("https://jsonplaceholder.typicode.com/posts/1") print(response.status_code) # 200 print(response.json()) # dict
Output:200 {'userId': 1, 'id': 1, 'title': '...', 'body': '...'}

2️⃣ POST Request

data = {"title": "My Post", "body": "Content", "userId": 1} response = requests.post( "https://jsonplaceholder.typicode.com/posts", json=data ) print(response.status_code) # 201 print(response.json())

3️⃣ Headers & Authentication

headers = { "Authorization": "Bearer YOUR_TOKEN", "Content-Type": "application/json" } response = requests.get("https://api.example.com/data", headers=headers)

4️⃣ Query Parameters

params = {"page": 1, "limit": 10, "search": "python"} response = requests.get("https://api.example.com/items", params=params) print(response.url) # https://api.example.com/items?page=1&limit=10&search=python

5️⃣ Error Handling

import requests try: response = requests.get("https://api.example.com/data", timeout=5) response.raise_for_status() # Raises if 4xx/5xx data = response.json() except requests.exceptions.Timeout: print("Request timed out") except requests.exceptions.HTTPError as e: print(f"HTTP Error: {e}") except requests.exceptions.ConnectionError: print("Connection failed")

6️⃣ Download a File

url = "https://example.com/image.png" response = requests.get(url) with open("image.png", "wb") as f: f.write(response.content) print("Downloaded!")
📝 Use 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)
Output:1

Common Mistakes

  • No timeout.
  • Ignoring status codes.
  • Logging auth tokens.

Practice Task

Call API with params and handle errors.
Study Links:

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

import asyncio async def greet(name): print(f"Hello, {name}!") await asyncio.sleep(1) # Non-blocking wait print(f"Goodbye, {name}!") asyncio.run(greet("Anu"))
Output:Hello, Anu! (1 second pause) Goodbye, Anu!

2️⃣ Running Multiple Tasks

import asyncio async def task(name, seconds): print(f"{name} started") await asyncio.sleep(seconds) print(f"{name} done after {seconds}s") async def main(): await asyncio.gather( task("Task A", 2), task("Task B", 1), task("Task C", 3) ) asyncio.run(main())
Output:Task A started Task B started Task C started Task B done after 1s Task A done after 2s Task C done after 3s

3️⃣ Async HTTP Requests (aiohttp)

import aiohttp import asyncio async def fetch(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: data = await response.json() return data async def main(): urls = [ "https://jsonplaceholder.typicode.com/posts/1", "https://jsonplaceholder.typicode.com/posts/2", "https://jsonplaceholder.typicode.com/posts/3" ] results = await asyncio.gather(*[fetch(url) for url in urls]) for r in results: print(r["title"]) asyncio.run(main())

4️⃣ Sync vs Async Comparison

SynchronousAsynchronous
Tasks run one after anotherTasks run concurrently
Blocks while waitingDoes other work while waiting
Simple to writeBetter performance for I/O
3 API calls × 1s = 3s total3 API calls × 1s = ~1s total
💡 Use async for I/O-bound tasks (API calls, file reads, DB queries). Use multiprocessing for CPU-bound tasks.

🔎 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())
Output:['A', 'B']

Common Mistakes

  • Forgetting await.
  • Calling blocking requests inside async.
  • Using async for CPU-heavy tasks.

Practice Task

Create three async fake API calls and gather results.
Study Links:

Testing in Python

Testing ensures your code works correctly. Python has built-in unittest and the popular pytest library.

1️⃣ Using unittest

import unittest def add(a, b): return a + b class TestMath(unittest.TestCase): def test_add_positive(self): self.assertEqual(add(2, 3), 5) def test_add_negative(self): self.assertEqual(add(-1, 1), 0) def test_add_zero(self): self.assertEqual(add(0, 0), 0) if __name__ == "__main__": unittest.main()
Run:python -m unittest test_math.py ... OK (3 tests)

2️⃣ Using pytest (Recommended)

# Install: pip install pytest def multiply(a, b): return a * b def test_multiply_positive(): assert multiply(3, 4) == 12 def test_multiply_zero(): assert multiply(5, 0) == 0 def test_multiply_negative(): assert multiply(-2, 3) == -6
Run:pytest test_math.py -v PASSED test_multiply_positive PASSED test_multiply_zero PASSED test_multiply_negative

3️⃣ Testing Exceptions

import pytest def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b def test_divide_by_zero(): with pytest.raises(ValueError): divide(10, 0)

4️⃣ Fixtures (Setup/Teardown)

import pytest @pytest.fixture def sample_list(): return [1, 2, 3, 4, 5] def test_sum(sample_list): assert sum(sample_list) == 15 def test_length(sample_list): assert len(sample_list) == 5
AssertionPurpose
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)
Output:2 passed

Common Mistakes

  • Only testing happy path.
  • Tests depend on execution order.
  • Using real external services in unit tests.

Practice Task

Write tests for grade calculator and email validator.
Study Links:

Docker for Python

Docker packages your Python app with all dependencies into a portable container.

1️⃣ Dockerfile for Python App

# Dockerfile FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 5000 CMD ["python", "app.py"]

2️⃣ Build & Run

# Build image docker build -t my-python-app . # Run container docker run -p 5000:5000 my-python-app # Run in background docker run -d -p 5000:5000 --name myapp my-python-app

3️⃣ Docker Compose (Multi-Service)

# docker-compose.yml version: "3.8" services: web: build: . ports: - "5000:5000" environment: - DATABASE_URL=postgresql://user:pass@db:5432/mydb depends_on: - db db: image: postgres:15 environment: POSTGRES_USER: user POSTGRES_PASSWORD: pass POSTGRES_DB: mydb volumes: - pgdata:/var/lib/postgresql/data volumes: pgdata:

4️⃣ Common Docker Commands

CommandPurpose
docker psList running containers
docker stop myappStop a container
docker logs myappView container logs
docker exec -it myapp bashEnter container shell
docker-compose upStart all services
docker-compose downStop all services

5️⃣ .dockerignore

# .dockerignore __pycache__ *.pyc venv/ .env .git node_modules
💡 Use multi-stage builds for smaller images: build in one stage, run in another.

🔎 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"]
Output:docker build -t myapp . docker run myapp

Common Mistakes

  • No .dockerignore.
  • Copying secrets into image.
  • Using development server in production.

Practice Task

Dockerize a Flask or FastAPI app.

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)

from flask import Flask, jsonify, request import sqlite3 from auth import token_required, create_token app = Flask(__name__) def get_db(): conn = sqlite3.connect("students.db") conn.row_factory = sqlite3.Row return conn @app.route("/api/login", methods=["POST"]) def login(): data = request.get_json() if data["username"] == "admin" and data["password"] == "secret": token = create_token("admin") return jsonify({"token": token}) return jsonify({"error": "Invalid credentials"}), 401 @app.route("/api/students", methods=["GET"]) @token_required def get_students(user): db = get_db() students = db.execute("SELECT * FROM students").fetchall() return jsonify([dict(s) for s in students]) @app.route("/api/students", methods=["POST"]) @token_required def add_student(user): data = request.get_json() db = get_db() db.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", (data["name"], data["age"], data["grade"])) db.commit() return jsonify({"message": "Student added"}), 201 if __name__ == "__main__": app.run(debug=True)

3️⃣ Testing (test_api.py)

import pytest from app import app @pytest.fixture def client(): app.config["TESTING"] = True with app.test_client() as client: yield client def test_login_success(client): response = client.post("/api/login", json={"username": "admin", "password": "secret"}) assert response.status_code == 200 assert "token" in response.get_json() def test_login_failure(client): response = client.post("/api/login", json={"username": "wrong", "password": "wrong"}) assert response.status_code == 401

4️⃣ Requirements & Run

# requirements.txt flask==3.0.0 PyJWT==2.8.0 pytest==7.4.0 # Install & Run pip install -r requirements.txt python app.py # Run Tests pytest tests/ -v

🎯 Project Checklist

FeatureConcepts Used
REST API endpointsFlask routes, JSON
Database CRUDSQLite, SQL queries
AuthenticationJWT tokens, decorators
Testingpytest, fixtures
DeploymentDocker, requirements.txt
🎉 Congratulations! You've completed the entire Python tutorial — from basics to building a full production-ready API!

🔎 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))
Output:A

Common Mistakes

  • Everything in one file.
  • No validation.
  • Hardcoded secrets.
  • No tests.

Practice Task

Build Student Management API with login, CRUD, search, pagination, tests, and Docker.

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")
Output:Enter name: Anu Enter age: 22 Hello Anu, next year you will be 23

Production Scope

In real backend apps, input comes from API request JSON, forms, files, queues, environment variables, or databases. Still, the same rule applies: validate before using.

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")
Output:No user found Age is available

Production Scope

Use 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

Do not write 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)
Output:[1, 2, 3, 4] [1, 2, 3, 4]

Deep Copy for Nested Data

import copy

original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0].append(99)

print(original)
print(deep)
Output:[[1, 2], [3, 4]] [[1, 2, 99], [3, 4]]

Production Scope

This matters in APIs, configs, cached data, default settings, request payloads, and tests. Accidental shared mutation is a common real-world bug.

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)
Output:[1, 4, 9, 16, 25] [4, 16] {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} {0, 1} 55

Common Mistake

Do not create very complex nested comprehensions. If it is hard to read, use a normal loop.

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"))
Output:True Report ready

Production Scope

Use pathlib for uploads, reports, local cache files, test fixtures, project paths, and cross-platform scripts.

Logging

Logging is the production replacement for print debugging. It records application events with levels.

LevelMeaning
DEBUGDetailed developer information
INFONormal application flow
WARNINGUnexpected but recoverable
ERROROperation failed
CRITICALSevere 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

Use logs for API requests, background jobs, errors, retries, audit trails, and troubleshooting. Never log passwords, tokens, or private data.

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}))
Output:Hello Anu

Production Scope

Use type hints in large projects, APIs, SDKs, service layers, and shared team code. Add mypy or pyright checks in CI for stronger quality.

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}")
Run:python greet.py Anu --times 2 Hello Anu Hello Anu

Production Scope

Use argparse for migration scripts, admin tools, report generators, deployment helpers, and automation commands.

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)
Output:development False

Production Scope

Never hardcode secrets. Use environment variables, AWS Secrets Manager, Parameter Store, Kubernetes secrets, or CI/CD secret storage.

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

Use subprocess for automation, build tools, CLI wrappers, git commands, system utilities, and deployment scripts. Prefer argument lists over shell=True.
Avoid 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)
Output:[1, 4, 9]

Production Scope

Use threads for parallel I/O. For CPU-heavy work, use multiprocessing or distributed workers.

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

Use multiprocessing for CPU-heavy analytics, image processing, simulations, and batch jobs. For web apps, use task queues like Celery/RQ for background jobs.
On Windows, always protect multiprocessing code with if __name__ == "__main__":.