while — Advanced Examples
Starts a loop that repeats as long as its condition is true
While for state machines
Using while loops to implement state-based logic.
python
def tokenize(expression): tokens = [] i = 0 while i < len(expression): ch = expression[i] if ch.isspace(): i += 1 elif ch.isdigit(): num = "" while i < len(expression) and expression[i].isdigit(): num += expression[i] i += 1 tokens.append(("NUM", int(num))) elif ch in "+-*/": tokens.append(("OP", ch)) i += 1 else: i += 1 return tokens result = tokenize("12 + 34 * 5") for token in result: print(token)
while loops are natural for parsers and state machines where the number of iterations depends on the input content, not just its length.
Want to try these examples interactively?
Open Advanced Playground