the full guide

Going further: None, formatting, generators and decorators

The remaining Python ideas you'll meet when reading real code.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

None: nothing here yet

None means “no value”. It isn't 0 and it isn't empty text. Check for it with is.

none_demo.py
best_score = None

if best_score is None:
    print("No score yet")

def say_hi():
    print("Hi")          # No return here

print(say_hi())          # So this gives None

Output

No score yet
Hi
None

Formatting numbers and text

formatting.py
price = 1234.5678

print(f"{price:.2f}")       # 2 digits after the decimal
print(f"{price:,.0f}")      # Commas, no decimals
print(f"{0.856:.1%}")       # As a percentage
print(f"[{'left':<8}]")     # Pad to 8 spaces, on the left
print(f"[{'right':>8}]")    # Pad on the right

Output

1234.57
1,235
85.6%
[left    ]
[   right]

Backslash starts a special character: \n is a new line and \t is a tab.

Iterators and generators

A generator makes values one at a time rather than storing them all. That's how training code feeds huge datasets to a model in small batches.

generators.py
def batches(data, size):
    for start in range(0, len(data), size):
        yield data[start:start + size]      # Hand one out, then pause here

for batch in batches([1, 2, 3, 4, 5], 2):
    print(batch)

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

Output

[1, 2]
[3, 4]
[5]
10
20

Decorators

A decorator wraps a function to add something extra. The @ line means “wrap the next function in this”. FastAPI and Flask routes use exactly this syntax.

decorators.py
def shout(function):
    def wrapper(*args):
        return function(*args).upper() + "!"
    return wrapper

@shout
def greet(name):
    return "hello " + name

print(greet("riya"))

Output

HELLO RIYA!

Finished reading?