Accumulating Results

Lesson 51 of 54 · Python Foundations

A loop can build a result one item at a time. The starting value matters: addition starts at zero, while multiplication starts at one.

def total_through(n: int) -> int:
    total = 0
    for number in range(1, n + 1):
        total += number
    return total

def factorial(n: int) -> int:
    if n < 0:
        raise ValueError("factorial requires a nonnegative integer")
    product = 1
    for number in range(1, n + 1):
        product *= number
    return product

print(total_through(4), total_through(0))
print(factorial(4), factorial(0))
10 0
24 1

range excludes its stop, so n + 1 includes n. For a number below one the first range is empty, leaving the sum at zero. The factorial function rejects negatives; its empty loop for zero leaves the product at one, the conventional value of zero factorial. For 4, its running product is 1 → 1 → 2 → 6 → 24. Both functions expect integers as their annotations state.

A minimum needs a different initial value. Positive infinity compares greater than finite numbers, so it can serve as a sentinel—an intentionally chosen starting value.

def smallest(values: list[float]) -> float:
    result = float("inf")
    for value in values:
        if value < result:
            result = value
    return result

print(smallest([3.0, -2.0, 7.0]))
print(smallest([]))
-2.0
inf

Here an empty list returns infinity by design, not a real minimum. Infinity itself is a floating-point value; not every numeric value is finite, and nan has special comparison behavior. Another interface might return None or raise instead. The built-in min is convenient when its behavior suits the application.