Vyper theorytheory 0/50 · 0%
Control flow · easy

9. Control flow: if and for

Branches and bounded loops — Vyper has no while loop.

`if`/`elif`/`else` behave as expected. Loops are more restricted than Solidity: Vyper only has `for`, and the loop bound must be known at compile time (a literal or a `range()` with a constant bound), which guarantees gas usage can't spiral out of control from a single call.

@external
@pure
def classify(n: int128) -> String[8]:
    if n > 0:
        return "positive"
    elif n < 0:
        return "negative"
    else:
        return "zero"

@external
@pure
def total(xs: uint256[5]) -> uint256:
    t: uint256 = 0
    for x in xs:
        t += x
    return t

There is no `while` loop and no `break`-free infinite loop — every loop must terminate by construction.

Check your understanding

  1. 1. Which loop construct does Vyper support?

  2. 2. Why must loop bounds be known at compile time?

  3. 3. Does Vyper support `while` loops?