Skip to content

Latest commit

 

History

History
282 lines (188 loc) · 5.33 KB

File metadata and controls

282 lines (188 loc) · 5.33 KB

🧭 Python for C++ Developers — “By Example” Learning Series

Each module will have:

  1. Concept focus
  2. C++ vs Python code comparison
  3. Why it’s different / how it works
  4. Mini practice exercises

📘 Module 1: Variables, Types, and Dynamic Typing

🧩 Concept

Python variables are references, not typed containers. Everything is an object, and types are checked at runtime.

🧠 Example: Dynamic typing

C++

int x = 10;
x = "hello"; // ❌ Compile-time error

Python

x = 10
x = "hello"   # ✅ Works fine; x now refers to a string

Explanation

  • In Python, variables are just names bound to objects.
  • The object has a type, not the variable.
  • Type errors only appear at runtime, not compile-time.

Exercise

a = 3.14
b = int(a)
a = "changed"
print(type(a), type(b))

Predict outputs and explain why types changed dynamically.


📘 Module 2: Indentation, Blocks, and No Braces

🧩 Concept

Indentation is syntax in Python. No {} or ;.

C++

if (x > 5) {
    cout << "big";
} else {
    cout << "small";
}

Python

if x > 5:
    print("big")
else:
    print("small")

Explanation

  • Python enforces indentation for readability.
  • No explicit block delimiters → less syntax noise.

Exercise Fix the indentation error:

for i in range(3):
print(i)

📘 Module 3: Lists vs Arrays

🧩 Concept

Python’s list is more like a std::vector<void*> — dynamic, heterogeneous, and resizeable.

C++

std::vector<int> nums = {1, 2, 3};
nums.push_back(4);

Python

nums = [1, 2, 3]
nums.append(4)
nums.append("five")   # ✅ heterogeneous elements allowed

Why it matters

  • Python lists are implemented as dynamic arrays of pointers.
  • All elements are references; type safety is relaxed.

Exercise

lst = [1, "two", [3]]
print(lst[2][0])

📘 Module 4: Functions as First-Class Objects

🧩 Concept

In Python, functions can be stored in variables, passed, and returned — like std::function on steroids.

C++

int add(int a, int b) { return a + b; }
auto f = add;
cout << f(2, 3);

Python

def add(a, b):
    return a + b

f = add
print(f(2, 3))

Extra power

def apply(fn, x, y):
    return fn(x, y)

print(apply(add, 2, 3))

Why it matters

  • Enables higher-order programming, decorators, callbacks.
  • You’ll use this concept in frameworks, async, and class methods.

📘 Module 5: Duck Typing and Polymorphism

🧩 Concept

C++: polymorphism through inheritance and virtual methods. Python: polymorphism through behavior (“if it quacks like a duck”).

C++

class Animal { public: virtual void speak() = 0; };
class Dog : public Animal { public: void speak() override { cout << "Woof"; } };

Python

class Dog:
    def speak(self): print("Woof")

class Cat:
    def speak(self): print("Meow")

def animal_sound(animal):
    animal.speak()   # no base class needed

animal_sound(Dog())
animal_sound(Cat())

Why it matters

  • Python relies on interfaces by behavior, not inheritance.
  • Encourages more flexible and decoupled designs.

📘 Module 6: Iterators and Comprehensions

🧩 Concept

Python loops and comprehensions are syntactic sugar for iterable protocols.

C++

std::vector<int> v = {1,2,3,4};
for (auto i : v) cout << i * 2;

Python

v = [1,2,3,4]
for i in v:
    print(i * 2)

# comprehension
doubles = [i * 2 for i in v]

Exercise Write a one-liner that creates a list of squares of even numbers from 0–10.


📘 Module 7: Memory & Object Model

🧩 Concept

  • Everything is a reference.
  • id(x) gives the memory address (conceptually).
  • is checks identity, not equality.
a = [1,2,3]
b = a
print(a is b)     # True
print(a == b)     # True

b = [1,2,3]
print(a is b)     # False (different objects)

Why it matters

  • Avoid mutable default arguments (common bug).
  • Understand reference semantics vs copy semantics.

📘 Module 8: Decorators, Generators, and Context Managers

These are the most “Pythonic” constructs with no direct C++ equivalent. We’ll explore:

  • @decorator syntax
  • yield generators (lazy evaluation)
  • with context managers (RAII-like cleanup)

(You’ll love these when we get to async and resource management.)


🧑‍💻 Plan of Progression

Phase Topics Focus
1 Modules 1–3 Syntax, types, collections
2 Modules 4–5 Functions, OOP, polymorphism
3 Modules 6–7 Iteration, memory model
4 Module 8 Advanced “Pythonic” features
5 Project Build a compact Python CLI or service (e.g., mini MQTT simulator or AWS data ingestor)