🧠 Chapter 12: Advanced Python 1 – Ultimate Notes & Explanations


1️⃣ Walrus Operator (:=)

✅ Concept:

The Walrus operator (:=) allows you to assign a value to a variable as part of an expression — combining assignment and condition check in one line.

🔍 Syntax:

if (n := len(my_list)) > 3:
    print(f"List is too long ({n} elements)")

🔁 Old Way vs New Way:

# Old Way
n = len(my_list)
if n > 3:
    ...

# With Walrus
if (n := len(my_list)) > 3:
    ...

📂 Code:

# walrus.py
if(n := len([1,2,3,4,5])) > 3:
    print(f"List is too long({n} elements, expected < 3)")
else:
    print("List is shorter than 3 elements")

2️⃣ Type Hints

✅ Concept:

Type Hints provide information to the reader and IDEs about what type a variable/function expects. It doesn't enforce anything but makes the code easier to understand and maintain.

🔧 Syntax:

def func(a: int, b: int) -> int:
    return a + b

📂 Code:

# typehints.py
from typing import Tuple

n: int = 5
name: str = "Prathamesh"

def sum(a: int, b: int) -> int:
    return a + b

person: tuple[int, str] = ("Prathamesh", 100)

print(sum(5, 5))
print(person, type(person))