``` Python Master Notes — Complete Documentation & Mastery Edition
Sheryians Coding School

Python
Complete Notes

From your very first line of code to advanced OOP — everything you need, in one place.

🎬 Watch alongside! This book is designed to work hand-in-hand with the video series on Sheryians AI on YouTube. Every concept here has a matching video explanation.

Complete Documentation Edition • Python 3.14 reference aligned • Interactive study workbook

Introduction

What is Python?

🐍 Python in Simple Words

Python is a high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. The name comes not from the snake, but from the British comedy show Monty Python's Flying Circus — because Guido wanted the language to be fun to use.

Python is designed to be simple to read and write. Its syntax looks almost like plain English, which is why it's the most beginner-friendly language in the world — and at the same time, powerful enough to run Instagram, YouTube, and NASA systems.

👶 Easy to Learn

No semicolons, no curly braces, no type declarations. Just clean, readable code that looks like English.

💪 Incredibly Powerful

Used in AI, web development, data science, automation, game dev, cybersecurity and more.

⚙️ How Does Code Actually Run?

Before Python makes sense, you need to understand how computers run code. There are two main approaches — Compiled and Interpreted.

🏗️ Compiled Languages — Build First, Run Later

Think of it like translating an entire book from Hindi to English before giving it to someone. The whole translation happens upfront — this is called compiling. Once compiled, the program runs extremely fast because the computer already has the translation ready.

📝 Source Code
🔨 Compiler
⚡ Machine Code
🖥️ Runs!

Examples: C, C++, Rust, Go

🎭 Interpreted Languages — Translate Line by Line

Think of it like a live interpreter at a conference who translates speech sentence by sentence as the speaker talks. There's no pre-translation — each line is read, translated, and executed one at a time.

📝 Source Code
🔄 Interpreter
(line by line)
🖥️ Runs!

Examples: Python, JavaScript, Ruby

🐍
Where does Python fit? Python is an interpreted language. When you run a Python file, the Python interpreter reads your code line by line and executes it immediately. That's why errors show up one at a time — it stops at the first problem it hits.

⚖️ Compiled vs Interpreted — Side by Side

FeatureCompiledInterpreted (Python)
TranslationAll at once before runningLine by line while running
Speed⚡ Faster execution🐢 Slightly slower
Error DetectionAll errors found before runningStops at the first error
PortabilityPlatform-specific binaryRuns anywhere Python is installed
Development SpeedSlower to write & test✅ Fast to write & test
ExamplesC, C++, Rust, GoPython, JavaScript, Ruby
💡
Fun fact: Python actually compiles your code to bytecode (.pyc files) first, then interprets that bytecode using the Python Virtual Machine (PVM). So technically it's a bit of both — but we call it interpreted because you never see or manage the compiled step.

🌍 Why Python? Where is it Used?

Python's simplicity and the massive ecosystem of libraries make it useful in almost every field of technology. Here's where Python truly shines:

🤖

AI & Machine Learning

Libraries like TensorFlow, PyTorch, and scikit-learn make Python the #1 language for AI. ChatGPT, Gemini, and most modern AI tools are built with Python.

📊

Data Science & Analytics

Pandas, NumPy, Matplotlib — companies use Python to analyse millions of rows of data and turn them into insights and charts.

🌐

Web Development

Django and Flask are powerful Python frameworks. Instagram, Pinterest, and Spotify's backend all run on Python.

⚙️

Automation & Scripting

Automate boring tasks — rename 1000 files, scrape websites, send automated emails, schedule tasks. Python makes it simple.

🔐

Cybersecurity

Python is the go-to language for ethical hacking and penetration testing. Tools like Metasploit and many security scripts are Python-based.

🎮

Game Development

Pygame lets you build 2D games with Python. It's a great way to practise programming while building something fun.

✨ Key Features of Python

🧹 Clean SyntaxReads like English. Indentation is mandatory, making all Python code look consistent.
🆓 Free & Open SourcePython is completely free to download, use, and distribute — even commercially.
📦 Huge Library EcosystemPyPI has over 400,000 packages. Whatever you want to build, there's probably already a library for it.
🌍 Cross-PlatformWrite once, run anywhere — Windows, macOS, Linux. Same Python code works on all of them.
🔗 Great CommunityMillions of developers, endless tutorials, Stack Overflow answers, and active forums.
🧩 Multi-ParadigmSupports functional, procedural, and object-oriented programming styles.

🐍 Python vs Other Languages — A Quick Taste

Let's print "Hello, World!" in three different languages to see how clean Python really is:

Java

public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }

5 lines just to print one thing 😅

🐍 Python

print("Hello, World!")

1 line. That's it. ✅

🚀
You're all set! Now that you know what Python is, where it came from, how it runs, and where it's used — let's get it installed and write some actual code. Head to Chapter 01!
Chapter 01

Installation

Downloading Python

  • Open any browser → go to python.org → download Python for your operating system.
  • Run the installer. This gives you the Python Virtual Machine which converts your code into byte code that your computer can run.
⚠️
ImportantCheck "Add Python to PATH" during installation on Windows — otherwise your terminal won't find Python!

Downloading an IDE

An IDE (Integrated Development Environment) is where you write and run your code. Popular choices are VS Code, PyCharm, and Jupyter — but we'll use VS Code throughout this book.

Setting Up VS Code

  • Open VS Code → go to the Extensions panel (Ctrl+Shift+X)
  • Search for and install: Python (by Microsoft) and Code Runner
  • Create a new file ending in .py and you're ready to go!

📘 Deep Dive & Practice

Environment Checklist

Learn the complete workflow: create a project folder, choose a Python interpreter, create a virtual environment, install dependencies, run the program, and read errors from the terminal.

python --version python -m venv .venv .venv\Scripts\Activate.ps1 python -m pip install --upgrade pip python -m pip freeze

Project Hygiene

  • One project per folder.
  • Use a virtual environment.
  • Keep dependencies documented.
  • Use a README.
  • Never store passwords/API keys directly in source code.
🧪
Lab: Create main.py, activate a virtual environment and print Python's version with sys.version.

📚 Documentation & Deep Dive: Environment & Tooling

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

python --version python -m pip --version python -m venv .venv python -m pip install -U pip
📌
Use a virtual environment per project; select the same interpreter in VS Code.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Installation

Concepts You Must Be Able To Explain

interpreter, PATH, venv, pip, IDE, debugger

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Installation practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Installation concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Create a virtual environment, install a package, freeze dependencies, and run a script from the terminal.

Self-Test Questions

Q1
What problem does Installation solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 02

Comments & Variables

Comments

Comments are notes you write in your code for yourself (or other developers). Python completely ignores them — they don't affect how the program runs.

# This is a single-line comment """ This is a multiline comment written using a docstring """
💡
Python doesn't have a true multiline comment syntax. We "borrow" the triple-quote string """...""" for this purpose.

Variables

Think of a variable as a labelled box — you put a value inside and refer to it by the label whenever you need it.

name = "Akarsh" age = 20 city = "Indore"
🚫
Rules — these will cause errors:
❌  1name = "x"  → can't start with a number
❌  my name = "x"  → no spaces allowed
❌  my-name = "x"  → no special characters (except underscore)

Naming Conventions

camelCase → myVariableName PascalCase → MyVariableName snake_case → my_variable_name # ✅ Python prefers this

📘 Deep Dive & Practice

Input → Convert → Validate

A reliable beginner program follows a simple pipeline: receive input, clean it, convert it, validate it, then use it.

age_text = input("Age: ").strip() if age_text.isdigit(): age = int(age_text) print("Next year:", age + 1) else: print("Enter a whole number.")

Dynamic Typing

Python variables are names bound to objects. The same name can later refer to another type, but clear programs still use meaningful names and predictable data.

Naming Rules

Prefer snake_case for variables/functions, PascalCase for classes and uppercase names for constants by convention.

📚 Documentation & Deep Dive: Names, Scope & Binding

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

name = "Hamza" age: int = 20 x = y = 0 a, b = 10, 20
📌
Names refer to objects. Assignment binds a name; it does not copy an object automatically.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Comments & Variables

Concepts You Must Be Able To Explain

names, assignment, scope, mutability, annotations

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Comments & Variables practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Comments & Variables concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Write a program that tracks a student profile and updates only the intended fields.

Self-Test Questions

Q1
What problem does Comments & Variables solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 03

Data Types

What are Data Types?

Every value in Python has a type that tells Python what kind of data it is and what you can do with it. You don't need to declare types — Python figures it out automatically.

The Main Data Types

intWhole numbers: 1, 42, -7
floatDecimal numbers: 3.14, -0.5
complexReal + imaginary: 3+4j
strText in quotes: "hello"
boolOnly two values: True or False
NoneTypeRepresents nothing: None

Checking the Type

print(type(42)) # <class 'int'> print(type(3.14)) # <class 'float'> print(type("hello")) # <class 'str'> print(type(True)) # <class 'bool'>

📘 Deep Dive & Practice

Operator Practice

a, b = 17, 5 print(a / b) print(a // b) print(a % b) print(a ** 2)

Useful Numeric Functions

Know abs(), round(), min(), max() and sum(). They appear constantly in real programs.

Mini Project

Build a bill calculator that accepts price, quantity and tax rate, then prints subtotal, tax and final amount to two decimal places.

📚 Documentation & Deep Dive: Built-in Types

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

type(42) # int type(3.14) # float type(True) # bool type(None) # NoneType
📌
Core built-ins include int, float, complex, bool, str, list, tuple, range, dict, set, frozenset, bytes, bytearray and memoryview.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Data Types

Concepts You Must Be Able To Explain

int, float, complex, bool, None, mutability

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Data Types practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Data Types concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a type-inspection utility that reports value, type and whether common containers are mutable.

Self-Test Questions

Q1
What problem does Data Types solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 04

Strings & Type Conversion

How Strings Work Internally

Each character in a string is stored with its own Unicode number. That's why strings use more memory than integers.

ord("A") # → 65 (Unicode of A) chr(65) # → "A" (Character from Unicode)

String Indexing

Every character in a string has a position number called an index. Positive indexes count from the left (starting at 0), negative from the right (starting at -1).

a = "Hello" # H e l l o # 0 1 2 3 4 ← positive # -5 -4 -3 -2 -1 ← negative print(a[0]) # H print(a[-1]) # o

String Slicing

Slicing cuts out a piece of a string. Syntax: string[start : stop : step] — note that stop index is excluded.

a = "hello" print(a[1:4]) # ell (index 1,2,3 — 4 excluded) print(a[::-1]) # olleh (reversed!)

Type Conversion

You can convert a value from one type to another using these built-in functions:

int()→ whole number
float()→ decimal number
str()→ text
bool()→ True or False

⚡ Implicit (Automatic)

Python converts automatically when needed.

a = 12 print(a / 2) # 6.0 # int ÷ int → float!

🔧 Explicit (Manual)

You tell Python to convert.

a = 12 a = str(a) print(a) # "12"

The 7 Falsy Values

Everything converts to True with bool()except these 7 values which become False:

0
0.0
False
""
[]
{}
()

📘 Deep Dive & Practice

Indexing and Slicing

text = "Python Programming" print(text[0]) print(text[-1]) print(text[:6]) print(text[7:]) print(text[::-1])

Essential Methods

name = " hamza sami " name = name.strip().title() print(name.replace(" ", "_")) print("Hamza" in name)

F-Strings

score = 92.456 print(f"Score: {score:.2f}%")
⚠️
Strings are immutable. Methods return a new string instead of changing the original object.

📚 Documentation & Deep Dive: Text, Unicode & Parsing

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

text = "Python 🐍" text.encode("utf-8") bytes([65, 66]) int("101", 2)
📌
Strings are immutable Unicode sequences. Use explicit encoding/decoding at I/O boundaries.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Strings & Type Conversion

Concepts You Must Be Able To Explain

Unicode, slicing, formatting, encoding, parsing

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Strings & Type Conversion practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Strings & Type Conversion concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a parser that converts user-entered marks and names into normalized records.

Self-Test Questions

Q1
What problem does Strings & Type Conversion solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 05

Input, Output & Operators

Output — print()

name = "Akarsh" age = 20 print("Hello!") # basic print(f"My name is {name}") # f-string print("Name:", name, "Age:", age) # multiple values

Input — input()

⚠️
Remember: input() always returns a string. If you need a number, convert it manually with int() or float().
name = input("What is your name? ") age = int(input("How old are you? ")) print(f"Hello {name}, you are {age} years old!")

Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.333…
//Floor Division10 // 33
%Modulus (remainder)10 % 31
**Exponentiation2 ** 8256

Comparison Operators

Always return True or False.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater or equal5 >= 5True
<=Less or equal3 <= 5True

Logical Operators

OperatorReturns True when…Example
andBoth conditions are Trueage > 18 and has_id == True
orAt least one condition is Trueis_admin or is_staff
notReverses the booleannot is_banned

Assignment Operators

OperatorMeaningEquivalent to
+=Add and assignx = x + n
-=Subtract and assignx = x - n
*=Multiply and assignx = x * n
/=Divide and assignx = x / n
//=Floor divide and assignx = x // n
%=Modulus and assignx = x % n
**=Power and assignx = x ** n

📘 Deep Dive & Practice

Building Decision Trees

marks = 78 if marks >= 80: grade = "A" elif marks >= 70: grade = "B" elif marks >= 60: grade = "C" else: grade = "F"

Guard Clauses

Reject invalid cases early rather than creating deeply nested conditions. This makes the main logic easier to read.

Truthiness

username = input("Username: ").strip() if not username: print("Username is required")

Practice

Create a login validator with empty-input checks, password length validation and role-based output.

📚 Documentation & Deep Dive: Expressions & Console I/O

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

name = input("Name: ") print(f"Hello, {name}") result = 10 // 3 mask = 0b1010 & 0b0110
📌
Understand precedence, short-circuit boolean operators, identity vs equality, and bitwise operators.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Input, Output & Operators

Concepts You Must Be Able To Explain

input, print, precedence, arithmetic, comparison, logical, bitwise

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Input, Output & Operators practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Input, Output & Operators concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a command-line calculator that validates input and handles integer and floating-point operations.

Self-Test Questions

Q1
What problem does Input, Output & Operators solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 06

Conditional Statements

Making Decisions in Code

Real programs don't run the same code every time — they make decisions. Conditional statements let your program choose what to do based on a condition. That's why they're also called control flow statements.

if condition: # runs when condition is True elif another_condition: # runs if the above was False, this is True else: # runs when nothing above was True

Types at a Glance

StatementWhen to use it
ifYou have one condition to check
if-elseTwo paths — True or False
if-elif-elseMultiple conditions checked one by one

📝 Practice Questions

Q1
Accept two numbers and print the greatest between them.
Input: 14, 7Output: 14 is greater
Q2
Accept gender from user and print a greeting message.
Input: MOutput: Good Morning Sir
Q3
Accept an integer and check if it is even or odd.
Input: 9Output: 9 is Odd
Q4
Accept name and age — check if the user is a valid voter (18+).
Input: Shery, 20Output: Hello Shery, you are a valid voter ✅
Q5
Accept a year and check if it is a leap year.
Input: 2024Output: 2024 is a leap year ✅
Q6 — Temperature Ladder
Accept temperature in °C and print a description.
Input: -5Freezing Cold 🥶
Input: 25Pleasant 😊
Input: 45Very Hot 🔥

📘 Deep Dive & Practice

Boolean Expressions

age = 21 has_id = True allowed = age >= 18 and has_id print(allowed)

Short-Circuit Evaluation

and and or may stop evaluating early. This is useful for safe guards and efficient conditions.

name = None if name is not None and len(name) > 3: print("Valid")

Equality vs Identity

Use == for value comparison and is when checking object identity, especially value is None.

📚 Documentation & Deep Dive: Branching & Pattern Matching

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

if score >= 80: print("A") elif score >= 60: print("B") else: print("C") match command: case "run": print("Running")
📌
Use conditions for decisions; use match when structural patterns make the logic clearer.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Conditional Statements

Concepts You Must Be Able To Explain

if, elif, else, truthiness, conditional expressions, match

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Conditional Statements practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Conditional Statements concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a grading/eligibility system with clear boundary conditions.

Self-Test Questions

Q1
What problem does Conditional Statements solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 07

Loops

Why Loops?

Imagine printing "Hello" 100 times. Without loops: 100 lines of code. With a loop: just 2 lines. Loops let you repeat a block of code without rewriting it.

Python has 2 types of loops: for and while.

The Bucket Analogy 🪣

Two buckets, one mug — which loop do you use?

🔢 FOR loop — known iterations

Transfer exactly 4 mugs. You know the count → use for.

🔁 WHILE loop — known condition

Transfer until bucket is empty. You don't know the count, but you know when to stop → use while.

📘 Deep Dive & Practice

For + Range

for i in range(1, 6): print(i) for i in range(10, 0, -2): print(i)

Loop Control

for n in range(1, 20): if n % 2 == 0: continue if n > 11: break print(n)

Nested Loops

Nested loops are useful for grids and tables, but remember that repeated work can grow quickly. Learn to estimate how many times the inner loop executes.

Challenge

Build a multiplication table and then upgrade your number-guessing game with limited attempts and a score.

📚 Documentation & Deep Dive: Iteration Control

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

for item in items: ... while condition: ... break continue
📌
Iterables produce values through iteration. Prefer clear loops; use enumerate and zip instead of manual indexing where appropriate.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Loops

Concepts You Must Be Able To Explain

iteration, break, continue, loop else, nesting

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Loops practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Loops concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a menu-driven program that keeps running until the user chooses exit.

Self-Test Questions

Q1
What problem does Loops solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 08

For Loop

The range() Function

range() generates a sequence of numbers. Think of it as saying "count from here to there".

range(stop) # 0 up to stop-1 range(start, stop) # start up to stop-1 range(start, stop, step)# start, jumping by step list(range(5)) # [0, 1, 2, 3, 4] list(range(1,6)) # [1, 2, 3, 4, 5] list(range(0,10,2)) # [0, 2, 4, 6, 8]

For Loop with Numbers

for i in range(1, 6): print(i) # Output: 1 2 3 4 5

For Loop with Strings

name = "hello" # Method 1 — via index for i in range(len(name)): print(name[i]) # Method 2 — direct (simpler!) for char in name: print(char)

break, continue & else — The Traffic Light Analogy 🚦

🚦 Imagine you're driving through 10 traffic signals on your way home

Each signal = one loop iteration. Here's what each keyword does:

🛑
break
You spot an accident ahead — you immediately stop and take a U-turn. Loop ends completely.
⏭️
continue
One signal is broken — you skip it and keep driving to the next one. Loop skips this iteration.
🏠
else
You crossed all signals with no problems — you reached home safely. Runs only when loop finishes without a break.
for i in range(1, 11): if i == 5: break # stop at signal 5 (accident!) if i == 3: continue # skip signal 3 (broken light) print(f"Signal {i} — passed ✅") else: print("Reached home safely! 🏠") # only if no break

📝 For Loop Questions

Q1
Print "Hello World" n times.
Input: 3Hello World × 3 lines
Q2
Print natural numbers from 1 to n.
Input: 51 2 3 4 5
Q3
Reverse for loop — print n down to 1.
Input: 55 4 3 2 1
Q4
Print the multiplication table of a number.
Input: 55×1=5, 5×2=10 … 5×10=50
Q5
Sum of first n natural numbers.
Input: 5Sum = 15
Q6
Factorial of a number.
Input: 55! = 120
Q7
Print sum of all even and odd numbers in a range separately.
Input: 1 to 10Even sum = 30, Odd sum = 25
Q8
Print all factors of a number.
Input: 121 2 3 4 6 12
Q9
Check if a number is perfect (sum of factors = the number itself).
Input: 66 is a Perfect Number ✅ (1+2+3=6)
Q10
Check if a number is prime.
Input: 1717 is Prime ✅Input: 99 is NOT Prime ❌
Q11
Reverse a string without using built-in functions.
Input: "Python"nohtyP
Q12
Check if a string is a palindrome.
Input: "racecar"Palindrome ✅Input: "hello"Not a palindrome ❌
Q13
Count letters, digits, and special symbols in a string.
Input: "P@#yn26at^&i5ve"Chars=8, Digits=3, Symbols=4

📘 Deep Dive & Practice

List Methods

items = ["pen", "book", "mouse"] items.append("keyboard") items.insert(1, "notebook") last = items.pop() items.sort() print(items, last)

Copying

a = [1, 2, 3] b = a.copy() b.append(4) print(a) print(b)

List Comprehensions

squares = [n*n for n in range(1, 11)] even = [n for n in range(20) if n % 2 == 0]

Use lists for ordered mutable collections. Avoid overly complicated comprehensions; readability comes first.

📚 Documentation & Deep Dive: For, Range & Iterables

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

for i in range(5): print(i) for i, value in enumerate(values): ... for a, b in zip(xs, ys): ... for key, value in mapping.items(): ...
📌
for works with any iterable, not only lists. range is lazy and supports start, stop, step.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: For Loop

Concepts You Must Be Able To Explain

iterables, range, enumerate, zip, nested loops

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# For Loop practice skeleton def solve(data): # 1. validate input # 2. transform/process it using For Loop concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Process two related lists and produce a formatted report without manual index arithmetic.

Self-Test Questions

Q1
What problem does For Loop solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 09

While Loop

While Loop

The while loop keeps running as long as a condition is True. You use it when you don't know how many times you'll need to repeat.

count = 1 while count <= 5: print(count) count += 1 # Output: 1 2 3 4 5
⚠️
Infinite Loop Danger! Always make sure your condition will eventually become False — otherwise your program runs forever!
💡
While loops also support break, continue, and else exactly like for loops.

📝 While Loop Questions

Q1
Separate each digit of a number and print on a new line.
Input: 12344 → 3 → 2 → 1
Q2
Accept a number and print its reverse.
Input: 1234554321
Q3
Check if a number is palindromic (equal to its reverse).
Input: 121Palindrome ✅Input: 123Not Palindrome ❌
Q4
Build a number guessing game — computer picks a random number, user keeps guessing until correct.
Guess: 50 → Too low! Guess: 75 → Too high! Guess: 63 → 🎉 Correct!

📘 Deep Dive & Practice

Tuples

point = (10, 20) x, y = point print(x, y)

Sets

skills = {"Python", "C#", "Python"} skills.add("Unity") print(skills)

Dictionaries

student = {"name": "Hamza", "gpa": 3.5} student["semester"] = 4 print(student.get("email", "Not provided")) for key, value in student.items(): print(key, value)

Decision Rule

Ordered collection → list/tuple. Unique values → set. Key-value lookup → dictionary.

📚 Documentation & Deep Dive: State-Based Repetition

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

while attempts < 3: ... while True: ... else: ... break
📌
Make loop termination explicit. Guard against infinite loops and update the state that controls the condition.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: While Loop

Concepts You Must Be Able To Explain

state, sentinel loops, validation, break, loop else

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# While Loop practice skeleton def solve(data): # 1. validate input # 2. transform/process it using While Loop concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a robust input-validation loop with retry limits and a clean exit path.

Self-Test Questions

Q1
What problem does While Loop solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 10

Functions

What are Functions?

A function is a reusable block of code with a name. Instead of writing the same logic 10 times, you write it once as a function and call it 10 times.

def greet(): print("Hello, welcome to Python!") greet() # ← this is calling the function

Parameters & Arguments

📋 Parameter

The variable name in the function definition. Like a placeholder.

def greet(name): # ← parameter ...

📦 Argument

The actual value you pass when calling the function.

greet("Alice") # ← argument

Types of Arguments

# 1. Positional — order matters def add(a, b): return a + b add(5, 3) # → 8 # 2. Default — works even without passing a value def greet(name="Guest"): print(f"Hello {name}") greet() # Hello Guest greet("Akarsh") # Hello Akarsh # 3. Keyword — pass in any order def info(name, age): print(f"{name} is {age}") info(age=25, name="Akarsh") # order doesn't matter

📘 Deep Dive & Practice

Return Values

def calculate_total(price, tax): return price + price * tax print(calculate_total(1000, 0.15))

Flexible Arguments

def add_all(*numbers): return sum(numbers) def profile(**data): return data

Type Hints and Docstrings

def area(radius: float) -> float: """Return circle area.""" return 3.14159 * radius ** 2

Refactoring Exercise

Take an earlier project and separate input, validation, business logic and output into different functions.

📚 Documentation & Deep Dive: Callable Objects & APIs

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

def add(a: int, b: int) -> int: return a + b def greet(name="World"): ... def f(*args, **kwargs): ... square = lambda x: x*x
📌
Functions support positional-only, positional-or-keyword and keyword-only parameters, defaults, annotations, closures and decorators.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Functions

Concepts You Must Be Able To Explain

parameters, return, defaults, keyword-only, args, kwargs, closures

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Functions practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Functions concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Refactor a long script into small testable functions with clear inputs and outputs.

Self-Test Questions

Q1
What problem does Functions solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 11

Data Structures

The 4 Built-in Data Structures

When you need to store multiple values in one variable, you use a data structure. Python gives you 4 ready to use:

StructureOrdered?Mutable?Duplicates?Access by
List✅ Yes✅ Yes✅ YesIndex
Tuple✅ Yes❌ No✅ YesIndex
Set❌ No✅ Yes❌ NoMethods
Dictionary✅ Yes✅ YesKeys: ❌Key

📘 Deep Dive & Practice

Import Patterns

import math from math import sqrt import random as rnd print(math.pi) print(sqrt(81)) print(rnd.randint(1, 10))

Your Own Module

# calculator.py def add(a, b): return a + b # main.py from calculator import add print(add(2, 3))

Main Guard

def main(): print("Started") if __name__ == "__main__": main()

Use modules to split large programs into focused files and reduce duplication.

📚 Documentation & Deep Dive: Containers & Algorithms

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

values = [3,1,2] unique = set(values) counts = {} pairs = [(1,"a"),(2,"b")]
📌
Choose a container based on access pattern: list for sequences, tuple for fixed records, set for uniqueness, dict for key/value lookup.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Data Structures

Concepts You Must Be Able To Explain

sequence vs mapping vs set, complexity, nesting, comprehensions

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Data Structures practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Data Structures concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Design the data model for a small student-management application before writing its logic.

Self-Test Questions

Q1
What problem does Data Structures solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 12

List

Creating and Accessing Lists

fruits = ["apple", "banana", "mango"] print(fruits[0]) # apple print(fruits[-1]) # mango print(fruits[0:2]) # ['apple', 'banana'] fruits[1] = "grape" # mutation — lists allow this!

Key List Methods

lst = [3, 1, 4, 1, 5] lst.append(9) # [3,1,4,1,5,9] — add to end lst.insert(0, 0) # [0,3,1,4,1,5,9] — insert at index lst.remove(1) # removes first 1 lst.pop() # removes last element lst.sort() # sort ascending lst.reverse() # reverse in place len(lst) # number of items

📝 List Questions

Q1
Print all positive and negative elements separately.
Input: [3, -1, 4, -5, 9]Positive: [3,4,9] Negative: [-1,-5]
Q2
Find the mean (average) of all list elements.
Input: [10, 20, 30, 40]Mean = 25.0
Q3
Find the greatest element and print its index.
Input: [4, 8, 2, 9, 1]Greatest = 9 at index 3
Q4
Find the second greatest element.
Input: [4, 8, 2, 9, 1]Second greatest = 8
Q5
Check if the list is already sorted.
Input: [1, 3, 5, 7]List is sorted ✅Input: [3, 1, 4]Not sorted ❌

📘 Deep Dive & Practice

Full Exception Flow

try: value = int(input("Number: ")) except ValueError: print("Invalid number") else: print(value ** 2) finally: print("Done")

Raise Your Own Errors

def withdraw(balance, amount): if amount < 0: raise ValueError("Negative amount") if amount > balance: raise ValueError("Insufficient balance") return balance - amount

Debugging Method

  1. Read the traceback.
  2. Locate the exact line.
  3. Inspect inputs.
  4. Reproduce with the smallest case.
  5. Fix the cause and retest.

📚 Documentation & Deep Dive: Mutable Sequence API

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

items.append(x) items.extend(other) items.insert(i, x) items.pop() items.remove(x) items.sort(key=..., reverse=True)
📌
Lists are dynamic arrays. Slicing creates a new list; assignment to a slice mutates the original.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: List

Concepts You Must Be Able To Explain

indexing, slicing, mutation, comprehensions, sorting, copying

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# List practice skeleton def solve(data): # 1. validate input # 2. transform/process it using List concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Implement filtering, sorting and pagination for a list of records.

Self-Test Questions

Q1
What problem does List solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 13

Tuple

Tuple — The Immutable List

A tuple is exactly like a list, except you cannot change it once created. Use tuples for data that should stay constant — like days of the week, coordinates, or config values.

days = ("Mon", "Tue", "Wed") print(days[0]) # Mon days[0] = "X" # ❌ TypeError — tuples are immutable

Tuple Methods (Only 2!)

t = (1, 2, 3, 2, 1) t.index(2) # → 1 (first position of 2) t.count(2) # → 2 (2 appears twice)

📘 Deep Dive & Practice

Text Files

with open("notes.txt", "w", encoding="utf-8") as f: f.write("Python\n") with open("notes.txt", "r", encoding="utf-8") as f: print(f.read())

Pathlib

from pathlib import Path path = Path("data") / "notes.txt" path.parent.mkdir(parents=True, exist_ok=True) path.write_text("Hello", encoding="utf-8") print(path.read_text(encoding="utf-8"))

JSON Persistence

Use JSON for simple structured application data such as settings, small databases and saved game state.

📚 Documentation & Deep Dive: Immutable Sequence API

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

point = (10, 20) x, y = point single = (42,) a, *middle, z = values
📌
Tuples are immutable but can contain mutable objects. They are useful for records, unpacking and hashable composite keys when contents are hashable.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Tuple

Concepts You Must Be Able To Explain

immutability, unpacking, starred unpacking, nested tuples

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Tuple practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Tuple concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Represent coordinates and records with unpacking and safe transformations.

Self-Test Questions

Q1
What problem does Tuple solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 14

Set

Set — Unique Values Only

A set automatically removes duplicates and has no guaranteed order. Great for checking membership and performing math-style set operations.

s = {1, 2, 2, 3, 3, 3} print(s) # {1, 2, 3} — duplicates removed!

Set Operations

a = {1, 2, 3, 4} b = {3, 4, 5, 6} a | b # Union → {1,2,3,4,5,6} a & b # Intersection → {3,4} a - b # Difference → {1,2} a ^ b # Symmetric diff→ {1,2,5,6}

📘 Deep Dive & Practice

Comprehensions

nums = range(1, 11) squares = [n*n for n in nums] unique_lengths = {len(w) for w in ["AI", "Python", "AI"]} lookup = {n: n*n for n in range(5)}

enumerate and zip

names = ["Ali", "Hamza", "Sara"] scores = [88, 92, 95] for i, name in enumerate(names, 1): print(i, name) for name, score in zip(names, scores): print(name, score)

sorted with key

Learn to sort objects using sorted(items, key=...). This is extremely useful for reports and rankings.

📚 Documentation & Deep Dive: Set Algebra & Membership

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

a | b a & b a - b a ^ b x in my_set
📌
Sets provide fast average-case membership and eliminate duplicates. frozenset is immutable and hashable.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Set

Concepts You Must Be Able To Explain

membership, union, intersection, difference, frozenset

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Set practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Set concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Compare two datasets and report common, missing and unique elements.

Self-Test Questions

Q1
What problem does Set solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 15

Dictionary

Key-Value Storage

A dictionary stores data as key: value pairs — like a real dictionary where you look up a word (key) to find its meaning (value).

person = {"name": "Akarsh", "age": 20, "city": "Indore"} # Read print(person["name"]) # Akarsh # Update person["age"] = 21 # Add new key person["course"] = "Python" # Delete del person["city"] # Traverse for key, val in person.items(): print(key, "→", val)

📝 Dictionary Questions

Q1
Merge two dictionaries into one.
d1={a:1}, d2={b:2}{a:1, b:2}
Q2
Sum all values in a dictionary.
{"a":10,"b":20,"c":30}Sum = 60
Q3
Count the frequency of each element in a list using a dictionary.
["a","b","a","c","b","a"]{"a":3,"b":2,"c":1}
Q4
Combine two dicts, adding values for common keys.
d1={a:5,b:3}, d2={b:4,c:2}{a:5, b:7, c:2}

📘 Deep Dive & Practice

Class Design

class Robot: def __init__(self, name, battery=100): self.name = name self.battery = battery def move(self, distance): self.battery -= distance return f"{self.name} moved {distance}m" r = Robot("R1") print(r.move(10))

Responsibilities

Give each class one clear job. A Student class should represent a student; a manager/service class can handle collections of students and operations.

Portfolio Challenge

Refactor your Student Management System into Student, Course and StudentManager.

📚 Documentation & Deep Dive: Mapping API

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

user = {"name":"Hamza"} user.get("age", 0) user.setdefault("score", 0) user.items() {k:v for k,v in pairs}
📌
Dictionaries preserve insertion order in modern Python. Keys must be hashable. Prefer get, setdefault and defaultdict when they improve clarity.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Dictionary

Concepts You Must Be Able To Explain

keys, values, items, get, update, setdefault, comprehensions

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Dictionary practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Dictionary concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a frequency counter and nested configuration dictionary.

Self-Test Questions

Q1
What problem does Dictionary solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 16

Exception Handling

Errors vs Exceptions

❌ Errors (unfixable)

  • SyntaxError — wrong syntax
  • IndentationError — bad spacing
  • TabError — mixing tabs/spaces

✅ Exceptions (handleable!)

  • ZeroDivisionError
  • TypeError
  • ValueError
  • FileNotFoundError

Handling Exceptions

try: result = 10 / 0 except ZeroDivisionError: print("Can't divide by zero!") else: print("Success:", result) finally: print("This always runs.")
KeywordPurpose
tryWrap the risky code
exceptHandle the exception
elseRuns only if no exception occurred
finallyAlways runs — good for cleanup
raiseManually throw your own exception

📘 Deep Dive & Practice

Inheritance Example

class Vehicle: def move(self): return "Moving" class Car(Vehicle): def move(self): return "Driving" class Drone(Vehicle): def move(self): return "Flying" for v in [Car(), Drone()]: print(v.move())

Polymorphism

Different objects can expose the same method and the caller can use them through the same interface. This is particularly useful in robotics simulations.

Composition

Prefer composition when an object “has a” component rather than “is a” specialized version of another object.

📚 Documentation & Deep Dive: Errors, Exceptions & Recovery

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

try: risky() except ValueError as e: ... else: ... finally: cleanup() raise RuntimeError("message") from e
📌
Catch only errors you can handle. Preserve context with exception chaining and use custom exceptions for domain-level failures.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Exception Handling

Concepts You Must Be Able To Explain

exception hierarchy, try/except/else/finally, raise, chaining

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Exception Handling practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Exception Handling concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Design an error policy for a CLI application and distinguish user errors from programmer bugs.

Self-Test Questions

Q1
What problem does Exception Handling solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 17

File Handling

File Modes

ModeMeaningCreates file?
'r'Read only❌ (must exist)
'w'Write (overwrites!)
'a'Append to end
'x'Create (fails if exists)

Reading & Writing

# Writing with open("notes.txt", "w") as f: f.write("Hello from Python!") # Reading with open("notes.txt", "r") as f: content = f.read() print(content) # Appending with open("notes.txt", "a") as f: f.write("\nAdded a new line!")
Always use the with statement — it automatically closes the file for you, even if an error occurs.

📘 Deep Dive & Practice

Properties

class Temperature: def __init__(self, celsius): self.celsius = celsius @property def celsius(self): return self._celsius @celsius.setter def celsius(self, value): if value < -273.15: raise ValueError("Invalid temperature") self._celsius = value

Encapsulation

Expose a clean public interface and keep internal implementation details private by convention. Properties are excellent for validation without changing how callers access an attribute.

📚 Documentation & Deep Dive: I/O, Paths & Serialization

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

from pathlib import Path path = Path("data.txt") text = path.read_text(encoding="utf-8") path.write_text("hello", encoding="utf-8")
📌
Use context managers for open resources. Prefer pathlib for paths and explicit encodings for text.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: File Handling

Concepts You Must Be Able To Explain

open, pathlib, encodings, JSON, CSV, context managers

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# File Handling practice skeleton def solve(data): # 1. validate input # 2. transform/process it using File Handling concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a file-based notes or expense tracker with safe reads and writes.

Self-Test Questions

Q1
What problem does File Handling solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 18

OOP in Python

Three Ways to Write the Same Program

# Imperative — simple but not reusable a, b = 5, 3 print(a + b) # Functional — reusable def add(a, b): return a + b # Object Oriented — scalable & organised class Calculator: def add(self, a, b): return a + b calc = Calculator() print(calc.add(5, 3))
🎯
OOP key concepts: Classes · Objects · Encapsulation · Inheritance · Polymorphism · Abstraction

📘 Deep Dive & Practice

Abstract Base Classes

from abc import ABC, abstractmethod class Sensor(ABC): @abstractmethod def read(self): pass class TemperatureSensor(Sensor): def read(self): return 24.5

Duck Typing

Python often focuses on whether an object supports the required behavior rather than whether it inherits from one exact class.

Robotics Connection

A navigation module can depend on a sensor interface while concrete implementations represent lidar, ultrasonic or camera sensors.

📚 Documentation & Deep Dive: Object Model & Design

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

class Robot: ... robot = Robot() isinstance(robot, Robot) hasattr(robot, "move")
📌
Design classes around behavior and invariants, not just data. Favor composition when inheritance does not express a true subtype relationship.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: OOP in Python

Concepts You Must Be Able To Explain

objects, classes, composition, inheritance, interfaces

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# OOP in Python practice skeleton def solve(data): # 1. validate input # 2. transform/process it using OOP in Python concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Model a small robotics system with Robot, Sensor and Controller classes.

Self-Test Questions

Q1
What problem does OOP in Python solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 19

Classes

Class = Blueprint

A class is a blueprint — like an architect's plan for a house. The plan itself isn't a house, but you can build many houses from it. Each house is an object.

class Dog: species = "Canis lupus" # ← Attribute def bark(self): # ← Method print("Woof!") my_dog = Dog() # create object print(my_dog.species) # Canis lupus my_dog.bark() # Woof!

📘 Deep Dive & Practice

Iterators

numbers = iter([10, 20, 30]) print(next(numbers)) print(next(numbers)) print(next(numbers))

Generators

def countdown(n): while n > 0: yield n n -= 1 for value in countdown(5): print(value)

Generators produce values lazily, which is useful for large files, streams, simulations and pipelines.

Challenge

Create a generator that yields only even numbers up to a limit.

📚 Documentation & Deep Dive: Class Definition & Namespace

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

class Student: school = "UET" def study(self): ... Student.__dict__
📌
Classes create objects and provide a namespace for methods and attributes. Class attributes are shared; instance attributes belong to individual objects.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Classes

Concepts You Must Be Able To Explain

class body, class attributes, instance attributes, methods, namespaces

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Classes practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Classes concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Create a Student class and explain which data is shared and which is per-instance.

Self-Test Questions

Q1
What problem does Classes solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 20

Objects

Objects = Instances of a Class

🏭
Think of a Bag Factory. The factory has a blueprint (class) that needs material, zips, and pockets. Reebok and Campus both use this blueprint but provide their own specifications — they become two different objects.
class Bag: def __init__(self, material, zips): self.material = material self.zips = zips reebok = Bag("leather", 3) # object 1 campus = Bag("nylon", 2) # object 2 print(reebok.material) # leather print(campus.material) # nylon

📘 Deep Dive & Practice

Functions as Objects

def shout(text): return text.upper() fn = shout print(fn("hello"))

Decorator Pattern

from functools import wraps def log_call(func): @wraps(func) def wrapper(*args, **kwargs): print("Calling", func.__name__) return func(*args, **kwargs) return wrapper @log_call def add(a, b): return a + b

Use Cases

Decorators are useful for logging, timing, caching, validation and access-control patterns.

📚 Documentation & Deep Dive: Identity, Equality & Lifecycle

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

a = object() id(a) a is b a == b
📌
Objects have identity, type and value/state. is tests identity; == tests equality as defined by the objects.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Objects

Concepts You Must Be Able To Explain

identity, equality, references, copying, lifecycle

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Objects practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Objects concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Demonstrate aliasing versus copying with nested mutable objects.

Self-Test Questions

Q1
What problem does Objects solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 21

Constructor

__init__ — The Constructor

The constructor is a special method that runs automatically the moment you create an object. You use it to set up the object's initial data.

self is the object itself — it's how the method knows which object's data to set.

class Student: def __init__(self, name, grade): self.name = name # stored on THIS object self.grade = grade s1 = Student("Akarsh", "A") s2 = Student("Shery", "B") print(s1.name) # Akarsh print(s2.name) # Shery

📘 Deep Dive & Practice

Context Managers

A context manager guarantees cleanup around a block. File handling with with open() is the most common example.

from contextlib import contextmanager @contextmanager def resource(): print("Acquire") try: yield "resource" finally: print("Release") with resource() as r: print(r)

Applications

  • Files
  • Locks
  • Database connections
  • Temporary resources
  • Timing scopes

📚 Documentation & Deep Dive: Initialization & Object Creation

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

def __init__(self, name): self.name = name def __new__(cls, ...): ... super().__init__()
📌
__init__ initializes an already-created instance; it does not allocate the object itself. __new__ controls creation and is used for advanced patterns.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Constructor

Concepts You Must Be Able To Explain

__new__, __init__, initialization, alternate construction

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Constructor practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Constructor concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Create an immutable-like value object and compare initialization with object creation.

Self-Test Questions

Q1
What problem does Constructor solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 22

Attributes & Methods

Attributes

Class Attribute

Shared by all objects of the class.

class Dog: species = "Canis" # class

Instance Attribute

Unique to each object.

def __init__(self, name): self.name = name # instance

Methods

class Example: count = 0 def instance_method(self): # needs self return "Works with object" @classmethod def class_method(cls): # needs cls return cls.count @staticmethod def static_method(): # needs neither return "Just a helper function"

📘 Deep Dive & Practice

Regex Basics

import re text = "Contact: hamza@example.com" match = re.search(r"[\w.-]+@[\w.-]+\.\w+", text) if match: print(match.group())

Core Functions

search() finds one match, findall() finds many, sub() replaces and fullmatch() validates the entire input.

Rule

Use regex for genuinely pattern-based text. For simple prefix, suffix or replacement tasks, normal string methods are usually clearer.

📚 Documentation & Deep Dive: Descriptors, Properties & Methods

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

@property def name(self): ... @name.setter def name(self, value): ... @staticmethod @classmethod
📌
Use properties to maintain invariants, classmethod for alternate constructors, staticmethod for logically grouped helpers.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Attributes & Methods

Concepts You Must Be Able To Explain

instance/class/static methods, properties, descriptors, binding

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Attributes & Methods practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Attributes & Methods concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Build a class that validates an attribute through a property and exposes an alternate constructor.

Self-Test Questions

Q1
What problem does Attributes & Methods solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 23

Inheritance

Child Inherits from Parent

Just like children inherit traits from parents, a child class automatically gets all attributes and methods of the parent class.

class Animal: def breathe(self): print("Breathing...") class Dog(Animal): # Dog inherits from Animal def bark(self): print("Woof!") d = Dog() d.breathe() # inherited from Animal ✅ d.bark() # Dog's own method ✅

Types of Inheritance

# Single — one parent class Child(Parent): ... # Multiple — two parents class Child(Parent1, Parent2): ... # MRO: Parent1's methods take priority # Multilevel — grandparent → parent → child class Child(Parent): def __init__(self, name, grade): super().__init__(name) # call Parent's __init__ self.grade = grade

📘 Deep Dive & Practice

Date and Time

from datetime import datetime, timedelta now = datetime.now() tomorrow = now + timedelta(days=1) print(now.strftime("%Y-%m-%d %H:%M")) print(tomorrow.date())

Randomness

import random print(random.randint(1, 10)) print(random.choice(["Easy", "Medium", "Hard"]))

Security Note

Use random for games and simulations. Use secrets for security-sensitive random tokens.

📚 Documentation & Deep Dive: Reuse & Method Resolution Order

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

class Child(Parent): ... super().method() Child.__mro__ isinstance(child, Parent)
📌
Python uses MRO to resolve attributes and methods. Multiple inheritance is supported; cooperative super() requires compatible signatures.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Inheritance

Concepts You Must Be Able To Explain

base classes, overriding, super, MRO, multiple inheritance

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Inheritance practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Inheritance concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Create a hierarchy only where the subtype relationship is meaningful, then inspect __mro__.

Self-Test Questions

Q1
What problem does Inheritance solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 24

Polymorphism

Same Name, Different Behaviour

Polymorphism = "many forms". The same method name behaves differently depending on which object calls it.

class Dog: def speak(self): print("Woof! 🐕") class Cat: def speak(self): print("Meow! 🐈") class Duck: def speak(self): print("Quack! 🦆") # Same function call — different results! for animal in [Dog(), Cat(), Duck()]: animal.speak()
🦆
Duck Typing: "If it walks like a duck and quacks like a duck — it's a duck." Python doesn't care about the type of object, only whether it has the method you're calling.

📘 Deep Dive & Practice

Assertions

def add(a, b): return a + b assert add(2, 3) == 5

Unit Testing

import unittest class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(2 + 3, 5) if __name__ == "__main__": unittest.main()

Debugging Checklist

  1. Reproduce.
  2. Minimize.
  3. Inspect values.
  4. Fix root cause.
  5. Add a regression test.

📚 Documentation & Deep Dive: Protocols & Duck Typing

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

def render(obj): obj.render() hasattr(obj, "render") from typing import Protocol
📌
Polymorphism often comes from shared behavior rather than a shared base class. Protocols can describe structural interfaces for static type checking.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Polymorphism

Concepts You Must Be Able To Explain

duck typing, protocols, overriding, structural interfaces

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Polymorphism practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Polymorphism concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Write one function that works with several unrelated classes sharing the same behavior.

Self-Test Questions

Q1
What problem does Polymorphism solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 25

Encapsulation

Hiding Internal Details

Encapsulation means keeping data safe inside a class and only exposing what's necessary. Think of it like a medicine capsule — the drug is inside, protected.

class BankAccount: def __init__(self): self.owner = "Akarsh" # public self._balance = 1000 # protected (convention) self.__pin = 1234 # private (enforced) def get_balance(self): # safe accessor return self._balance acc = BankAccount() print(acc.owner) # ✅ Akarsh print(acc._balance) # ⚠️ works but bad practice print(acc.__pin) # ❌ AttributeError

📘 Deep Dive & Practice

Dataclasses

from dataclasses import dataclass @dataclass class Student: name: str semester: int gpa: float = 0.0 s = Student("Hamza", 4, 3.5) print(s)

Type Hints

def average(values: list[float]) -> float: return sum(values) / len(values) scores: list[int] = [80, 90, 95]

Type hints improve readability and editor/static-analysis support; Python normally does not enforce them at runtime.

📚 Documentation & Deep Dive: Visibility Conventions & Properties

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

self._value self.__secret @property
📌
Encapsulation in Python is mostly convention plus name mangling, not strict private fields. Keep invariants behind methods/properties when useful.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Encapsulation

Concepts You Must Be Able To Explain

conventions, underscore, name mangling, properties, invariants

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Encapsulation practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Encapsulation concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Protect a class invariant such as non-negative balance through a property or method.

Self-Test Questions

Q1
What problem does Encapsulation solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 26

Abstraction

Hide Complexity, Show Simplicity

Abstraction means showing only what the user needs to see, and hiding how it actually works. Like a TV remote — you press a button, you don't need to know the electronics inside.

from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): # defined, not implemented pass class Circle(Shape): def __init__(self, r): self.r = r def area(self): return 3.14 * self.r ** 2 c = Circle(5) print(c.area()) # 78.5

📘 Deep Dive & Practice

Good Abstraction

A good abstraction exposes a small interface representing a meaningful responsibility while hiding unnecessary implementation details.

from abc import ABC, abstractmethod class Storage(ABC): @abstractmethod def save(self, data): pass class MemoryStorage(Storage): def __init__(self): self.items = [] def save(self, data): self.items.append(data)

Project Challenge

Create a storage interface for an AI application, then implement memory storage and JSON-file storage without changing the application logic.

📚 Documentation & Deep Dive: Abstract Interfaces

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): ...
📌
Abstract base classes define required behavior. Protocols are another option when structural typing is preferable.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Abstraction

Concepts You Must Be Able To Explain

ABC, abstractmethod, protocols, interfaces

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Abstraction practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Abstraction concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Define an abstract sensor interface and implement two concrete sensor classes.

Self-Test Questions

Q1
What problem does Abstraction solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 27

Dunder Methods

Magic Methods

Dunder (double underscore) methods let your objects behave like built-in Python types. They're called automatically when you use operators or built-in functions.

class Vector: def __init__(self, x, y): self.x, self.y = x, y def __str__(self): # called by print() return f"({self.x}, {self.y})" def __add__(self, other): # called by + return Vector(self.x + other.x, self.y + other.y) def __len__(self): # called by len() return 2 v1 = Vector(1, 2) v2 = Vector(3, 4) print(v1) # (1, 2) print(v1 + v2) # (4, 6) print(len(v1)) # 2

📘 Deep Dive & Practice

Common Dunder Methods

class Vector: def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return f"Vector({self.x}, {self.y})" def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __eq__(self, other): return self.x == other.x and self.y == other.y

Other useful methods include __len__, __iter__, __getitem__, __contains__, __enter__ and __exit__.

📚 Documentation & Deep Dive: Data Model & Special Methods

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

__repr__ __str__ __len__ __iter__ __eq__ __lt__ __add__
📌
Special methods integrate user-defined classes with Python syntax and built-ins. Implement only the semantics that make sense for your type.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Dunder Methods

Concepts You Must Be Able To Explain

__repr__, __str__, __eq__, __lt__, __len__, __iter__, operators

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Dunder Methods practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Dunder Methods concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Create a Vector or Money class that behaves naturally with print, comparisons and operators.

Self-Test Questions

Q1
What problem does Dunder Methods solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Chapter 28

Advanced Topics

Decorators

A decorator wraps a function to add extra behaviour without modifying its code. Think of it as gift wrapping — the gift (function) is still the same, but it now has a wrapper around it.

def timer(func): def wrapper(): print("⏱ Starting...") func() print("✅ Done!") return wrapper @timer def greet(): print("Hello!") greet() # ⏱ Starting... # Hello! # ✅ Done!

*args and **kwargs

When you don't know how many arguments a function will receive, use *args (for positional) and **kwargs (for keyword).

def total(*args): # args is a tuple return sum(args) print(total(1, 2, 3, 4)) # 10 print(total(10, 20)) # 30 def profile(**kwargs): # kwargs is a dict for k, v in kwargs.items(): print(f"{k}: {v}") profile(name="Akarsh", age=20)

Comprehensions — One-liners

# List comprehension squares = [x**2 for x in range(5)] # [0,1,4,9,16] evens = [x for x in range(10) if x%2==0] # [0,2,4,6,8] # Dict comprehension squared = {x: x**2 for x in range(5)} # {0:0,1:1,2:4...} # Set comprehension unique = {x%3 for x in range(10)} # {0,1,2}

Lambda Functions

# Lambda = anonymous one-line function square = lambda x: x ** 2 add = lambda a, b: a + b check = lambda x: "even" if x%2==0 else "odd" print(square(5)) # 25 print(add(3, 7)) # 10 print(check(4)) # even

map(), filter(), zip()

nums = [1, 2, 3, 4, 5] # map — transform every item doubled = list(map(lambda x: x*2, nums)) # [2,4,6,8,10] # filter — keep items that pass the test evens = list(filter(lambda x: x%2==0, nums)) # [2,4] # zip — combine two lists into pairs names = ["A", "B", "C"] scores = [90, 85, 78] pairs = list(zip(names, scores)) # [('A',90),('B',85),...]

Modules & Packages

# Built-in modules import math import random from datetime import datetime print(math.sqrt(16)) # 4.0 print(random.randint(1, 100)) # random number print(datetime.now()) # current date/time # Third-party (install with pip) # pip install numpy pandas matplotlib

🚀 Advanced Challenge Questions

Pattern 1
Print a right-angle triangle with stars.
Input: 4* / ** / *** / ****
Pattern 2
Print a mirrored right-angle triangle.
Input: 4**** / *** / ** / *
Pattern 3
Print a centred diamond with stars.
Input: 5Diamond shape
Q1 — Strong Number
A number is strong if sum of factorials of its digits equals the number.
Input: 145Strong ✅ (1!+4!+5! = 145)
Q2 — Prime Range
Print all prime numbers between two numbers.
Input: 10, 3011 13 17 19 23 29
Q3 — Most Frequent
Find which element occurred most in a list.
Input: [1,3,3,2,1,3,4]3 (appeared 3 times)

📘 Deep Dive & Practice

Project Architecture

my_project/ ├── app/ │ ├── main.py │ ├── models.py │ └── services.py ├── tests/ │ └── test_services.py ├── requirements.txt └── README.md

Separation of Concerns

Separate input/output, business logic, data access and configuration as projects grow.

Optimization Rule

Make code correct first, readable second, and optimize measured bottlenecks third. Do not optimize based only on guesses.

📚 Documentation & Deep Dive: Production Python

Reference mindset: Learn the concept, know its syntax, understand its edge cases, then practise it in a small program. The official Python documentation separates the informal Tutorial, the exact Language Reference, and the Standard Library reference. This section gives you a practical bridge between those documents.

Core API / Syntax Reference

from dataclasses import dataclass from functools import lru_cache from contextlib import contextmanager async def fetch(): ... from concurrent.futures import ThreadPoolExecutor
📌
Advanced Python includes iterators, generators, comprehensions, decorators, context managers, typing, dataclasses, async programming, concurrency, testing, packaging and performance.

Common Mistakes

  • Confusing syntax errors with runtime errors.
  • Changing mutable objects when you intended to create a new value.
  • Ignoring edge cases such as empty input, missing keys, invalid types, and boundary values.
  • Writing code that works once but is difficult to test, reuse or maintain.

Practice Ladder

  1. Recall: explain the concept without looking at the notes.
  2. Implement: write a small example from memory.
  3. Modify: change the example to handle a new requirement.
  4. Debug: deliberately introduce an error and diagnose it.
  5. Build: use the concept in a mini-project.

🚀 Mastery Pack: Advanced Topics

Concepts You Must Be Able To Explain

iterators, generators, decorators, context managers, typing, dataclasses, async, concurrency

  • Define each term in your own words.
  • Show the simplest valid syntax.
  • Explain what happens at runtime.
  • Identify at least one common failure mode.
  • Choose the feature only when it makes the code clearer.

Worked Example Pattern

# Advanced Topics practice skeleton def solve(data): # 1. validate input # 2. transform/process it using Advanced Topics concepts # 3. return a predictable result return data if __name__ == "__main__": sample = [] print(solve(sample))

Exercises — Easy → Hard

  1. Write a minimal example from memory.
  2. Change one requirement without breaking the program.
  3. Add validation and meaningful error messages.
  4. Split the solution into reusable components.
  5. Add tests for normal, boundary and invalid cases.
  6. Refactor the solution for readability and maintainability.

Mini Project

Combine dataclasses, logging, tests and a generator into a small production-style project.

Self-Test Questions

Q1
What problem does Advanced Topics solve, and when should you avoid overusing it?
Q2
What is the difference between the simplest working solution and a maintainable solution?
Q3
What edge case would most likely break your first implementation?
Q4
How would you test this chapter's feature without relying only on manual execution?
Q5
How does this topic connect to real applications such as AI, automation, robotics or web development?
Bonus Module

Python Learning Roadmap

🎯 What to Learn Next

This section turns the notes into a practical learning path. Move from syntax → problem solving → real projects → libraries → specialization.

28+Core chapters
4Learning stages
10+Project ideas
1Goal: build independently
STAGE 1

Python Foundations

Variables, types, strings, input/output, operators, conditions, loops and functions. Focus on writing code without copying.

STAGE 2

Problem Solving

Lists, tuples, sets, dictionaries, nested loops, functions, recursion, patterns and algorithmic thinking.

STAGE 3

Real Python

Exceptions, files, modules, packages, virtual environments, debugging, testing and clean project structure.

STAGE 4

Specialize

Choose AI/ML, automation, web development, data science, robotics, computer vision or another Python ecosystem.

RULE

70% Practice

Spend most of your study time coding. Read a concept, close the notes, then rebuild it from memory.

RULE

Build Every Week

Even a small calculator, CLI game or file organizer teaches more than passively reading many pages.

🧠 Recommended Study Loop

1️⃣
LEARN
Read one concept and understand why it exists.
2️⃣
REBUILD
Type the examples yourself instead of copy/paste.
3️⃣
APPLY
Solve 3–5 variations without looking at the solution.

🚀 Expanded Guide

Stage 1 — Core Python

Syntax → variables → types → conditions → loops → functions → collections.

Stage 2 — Intermediate

Modules → exceptions → files → OOP → testing → environments → packages.

Stage 3 — Advanced

Generators → decorators → context managers → typing → dataclasses → architecture.

Stage 4 — AI & Robotics

NumPy → Pandas → Matplotlib → OpenCV → PyTorch → ROS 2 Python nodes → computer vision → AI inference.

Bonus Module

Python Quick Cheat Sheet

⚡ Syntax You Should Remember

TaskSyntaxExample
Variablename = valuescore = 95
Conditionif condition:if score >= 50:
Loopfor x in iterable:for n in numbers:
Functiondef name(...):def add(a,b):
List[a, b, c]nums = [1,2,3]
Dictionary{key: value}{"name":"Ali"}
Exceptiontry / excepttry: ... except ValueError: ...
Filewith open(...) as f:with open("data.txt") as f:

🔑 Useful Built-ins

len()Number of items/characters
range()Generate a sequence of numbers
enumerate()Get index + value while iterating
zip()Pair multiple iterables
sum()Add numeric items
sorted()Return a sorted copy
min() / max()Find smallest/largest value
any() / all()Test boolean conditions across iterables

🚀 Expanded Guide

Core Syntax

name = "Hamza" if score >= 50: print("Pass") for item in items: print(item) def add(a, b): return a + b

Collections

items = [] point = (10, 20) unique = set() profile = {"name": "Hamza"}

Terminal

python --version python -m pip list python -m pip freeze python -m unittest
Bonus Module

Project-Based Practice

🛠️ Build These in Order

01 — Calculator CLI

Use input, conversion, operators, functions and exception handling. Add a loop so the user can perform multiple calculations.

02 — Number Guessing Game

Use random, loops, conditions, difficulty levels, score tracking and replay functionality.

03 — Student Management System

Use lists/dictionaries first, then refactor into classes. Add search, update, delete and file persistence.

04 — Expense Tracker

Store expenses with date, category and amount. Add totals, category summaries and CSV/JSON persistence.

05 — File Organizer

Use pathlib and file handling to automatically organize files into folders by extension.

06 — Quiz Application

Load questions from JSON, randomize them, calculate scores and show performance at the end.

07 — AI/ML Starter Project

After mastering the basics, learn NumPy, Pandas and Matplotlib, then build a small data analysis or machine-learning project.

🚀 Expanded Guide

Project Workflow

  1. Write requirements.
  2. Break into functions/classes.
  3. Choose data structures.
  4. Validate input.
  5. Add persistence if needed.
  6. Test important cases.
  7. Refactor duplication.
  8. Document how to run it.

Upgrade Ladder

Start CLI → add validation → persistence → tests → GUI/API → database → deployment.

Bonus Module

Progress Checklist

✅ Track Your Skills

Your checklist is saved automatically in this browser using local storage.

A message from the creator

"We'll be learning all of this and so much more on this channel. I, Akarsh Vyas, as a creator and representative of Sheryians AI, would like to sincerely thank each and every one of you who stayed with us till the end. You are truly precious to us. Much love! 💙"

Sheryians Coding School

REFERENCE

Python Documentation & Complete Reference

📖 How Python's Documentation Is Organized

The official Python documentation is not one single tutorial. It is a documentation set containing a beginner-friendly Tutorial, a precise Language Reference, the Standard Library reference, setup/usage guides, HOWTOs, packaging guidance, C/API material, FAQs, deprecations, indexes and a glossary. The current official docs available at the time these notes were enhanced are for Python 3.14.6.

🎓 Tutorial

Learn the language progressively and informally. Best for first learning and guided practice.

⚖️ Language Reference

Precise syntax and core semantics: lexical analysis, data model, expressions, statements, execution model, imports and grammar.

📦 Library Reference

Built-in functions, built-in types, exceptions and the standard library modules.

🛠️ HOWTOs

Deep practical guides for focused topics such as logging, descriptors, regular expressions, sockets and more.

🧠 Language Reference Checklist

Lexical analysisLine structure, indentation, identifiers, keywords, literals, strings, bytes, numbers, operators and delimiters.
Data modelObjects, values, types, mutability, special methods, coroutines and object identity.
Execution modelProgram structure, namespaces, scopes, name binding, exceptions and runtime components.
Import systemModules, packages, importlib, search paths, loaders, finders and relative imports.
ExpressionsCalls, attribute access, subscriptions, slicing, await, arithmetic, bitwise operations, comparisons, boolean operations, assignment expressions, lambdas and precedence.
StatementsAssignment, assert, pass, del, return, yield, raise, break, continue, import, global, nonlocal and type statements.
Compound statementsif, while, for, try, with, match, function definitions, class definitions and coroutines.
GrammarThe formal grammar provides the syntax foundation for the language.

🧰 Built-in Functions Reference Map

AreaFunctions to masterTypical use
Input/outputprint(), input(), open()Console and file I/O
Conversionbool(), int(), float(), complex(), str(), bytes(), bytearray()Convert values
Collectionslist(), tuple(), set(), frozenset(), dict()Create containers
Iterationiter(), next(), enumerate(), zip(), reversed(), range()Build iteration pipelines
Inspectiontype(), isinstance(), issubclass(), dir(), vars(), id(), callable()Understand objects
Aggregationlen(), sum(), min(), max(), all(), any()Compute collection properties
Functionalmap(), filter(), sorted(), abs(), round()Transform and order data
Executioneval(), exec(), compile()Dynamic execution; use with extreme caution
Attributesgetattr(), setattr(), hasattr(), delattr()Dynamic object access

📦 Standard Library — What You Should Know

Module / PackagePurposeLearn these first
pathlibFilesystem pathsPath, exists, glob, read_text, write_text
os / shutilOS and file operationsenviron, walk, copy, move, rmtree
sysInterpreter/runtime informationargv, path, exit, version, stdin/stdout/stderr
jsonJSON serializationload, loads, dump, dumps
csvCSV datareader, writer, DictReader, DictWriter
sqlite3Embedded SQL databaseconnect, cursor, execute, commit
datetimeDates and timesdate, datetime, timedelta, timezone
reRegular expressionscompile, search, match, findall, sub
math / statisticsNumerical utilitiessqrt, ceil, floor, mean, median
randomPseudorandom generationrandint, choice, shuffle, sample
collectionsSpecialized containersCounter, defaultdict, deque, namedtuple
itertoolsIterator building blockschain, product, permutations, combinations
functoolsFunctional helpersreduce, partial, wraps, lru_cache
contextlibContext manager helperscontextmanager, suppress, ExitStack
dataclassesData-focused classesdataclass, field, asdict
typingStatic type annotationsTypeVar, Generic, Protocol, TypedDict, Literal
loggingApplication loggingLogger, levels, handlers, formatters
argparseCLI argument parsingArgumentParser, add_argument
subprocessRun external programsrun, Popen, CompletedProcess
threading / multiprocessingConcurrencyThread, Lock, Process, Queue
asyncioAsynchronous I/Oasync, await, Task, gather
unittestTestingTestCase, assert methods, mock

🔤 Complete Built-in Type Study Map

  • Numeric: int, float, complex, bool.
  • Sequences: list, tuple, range, str.
  • Binary: bytes, bytearray, memoryview.
  • Mappings: dict.
  • Sets: set, frozenset.
  • Iteration: iterator and generator protocols.
  • Callables: functions, methods, classes and callable instances.
  • Context managers: objects implementing __enter__ and __exit__.
  • Exceptions: BaseException hierarchy and custom exception classes.

🔁 Iterators & Generators

An iterable can produce an iterator. An iterator implements the iterator protocol, especially __iter__() and __next__(). Generators provide a convenient way to create iterators with yield.

def countdown(n): while n: yield n n -= 1 for value in countdown(3): print(value)

Use generators for streaming data and memory-efficient pipelines. Remember that a generator is consumed as you iterate over it.

🎯 Decorators

from functools import wraps def log_call(func): @wraps(func) def wrapper(*args, **kwargs): print("Calling", func.__name__) return func(*args, **kwargs) return wrapper @log_call def add(a, b): return a + b

Decorators receive a callable and return a callable. functools.wraps preserves useful metadata such as __name__ and __doc__.

🧩 Context Managers

with open("data.txt", encoding="utf-8") as file: text = file.read()

The with statement delegates setup and cleanup to a context manager. It is central to safe file handling, locks, database connections and resource management.

🧪 Testing Documentation

import unittest def add(a, b): return a + b class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) if __name__ == "__main__": unittest.main()

Test normal cases, boundary cases and failure cases. Keep tests deterministic and isolate external resources where practical.

📝 Type Hints

from typing import Iterable def total(values: Iterable[float]) -> float: return sum(values)

Annotations document intended interfaces and enable static analysis. Python remains dynamically typed at runtime; annotations do not automatically enforce types.

📊 Dataclasses

from dataclasses import dataclass @dataclass class Student: name: str age: int student = Student("Hamza", 20) print(student)

Dataclasses reduce boilerplate for data-centric classes by generating methods such as __init__ and __repr__, with configurable equality and ordering behavior.

⚡ Async Programming

import asyncio async def job(name): await asyncio.sleep(1) return name async def main(): results = await asyncio.gather(job("A"), job("B")) print(results) asyncio.run(main())

asyncio is designed for concurrent I/O-bound work. async defines a coroutine function; await suspends it while another task can make progress.

🧵 Threads vs Processes vs Async

ToolBest fitKey idea
asyncioMany I/O tasksCooperative concurrency
threadingI/O and blocking librariesMultiple threads in one process
multiprocessingCPU-heavy Python workSeparate processes

Choose based on workload and library behavior, not because one model is universally faster.

📦 Packaging & Virtual Environments

python -m venv .venv # Windows PowerShell .venv\Scripts\Activate.ps1 # install dependencies python -m pip install requests # export a simple dependency list python -m pip freeze > requirements.txt

For modern projects, learn pyproject.toml, build backends, package metadata, wheels, source distributions, dependency specifications and publishing workflows. Keep development environments isolated.

🖥️ Command-Line Applications

import argparse parser = argparse.ArgumentParser(description="Demo CLI") parser.add_argument("name") args = parser.parse_args() print(f"Hello {args.name}")

argparse is included in the standard library and is a strong foundation for portable CLI tools.

📋 Logging

import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("Application started") logger.warning("Something needs attention")

Prefer logging over print statements for applications that need levels, timestamps, handlers, files or structured operational output.

🔐 Security Rules

  • Never execute untrusted input with eval() or exec().
  • Do not deserialize untrusted pickle data.
  • Validate paths and user-controlled filenames.
  • Do not hard-code passwords, tokens or API keys.
  • Use HTTPS and secure credential storage for network applications.
  • Keep dependencies updated and inspect dependency provenance.

🚀 Performance Checklist

  1. Measure first with profiling tools.
  2. Choose appropriate data structures and algorithms.
  3. Avoid unnecessary repeated work.
  4. Use generators for streaming pipelines.
  5. Use caching when repeated computation is expensive.
  6. Move CPU-heavy work to suitable native/vectorized libraries or processes when appropriate.
  7. Do not sacrifice readability for tiny speculative optimizations.

📚 Official Documentation Links

⚠️
Important: “All documentation” is too large to reproduce verbatim in one HTML file. This workbook therefore adds a broad, structured reference and direct links to the official documentation. The official manuals remain the authoritative source for exact behavior and version-specific details.

🎓 Final Mastery Checklist

☐ SyntaxCan you read and write ordinary Python without looking up basic syntax?
☐ Data structuresCan you choose list, tuple, set or dict based on the problem?
☐ FunctionsCan you design clean reusable functions with sensible interfaces?
☐ ExceptionsCan you distinguish expected failures from programmer bugs?
☐ FilesCan you safely read/write text, JSON, CSV and paths?
☐ OOPCan you use classes without overusing inheritance?
☐ AdvancedCan you explain generators, decorators, context managers and async?
☐ ToolingCan you use venv, pip, tests, logging and a debugger?
☐ ProjectsCan you build a complete CLI or small application from scratch?
☐ DocumentationCan you navigate the Tutorial, Language Reference and Library Reference to solve unfamiliar problems?