whileExpert Examples

Starts a loop that repeats as long as its condition is true

While True patterns and bytecode

Idiomatic infinite loops and their compilation.

python
import dis

# while True is optimized in CPython
def infinite_pattern():
    while True:
        break

def conditional_pattern():
    x = True
    while x:
        break

print("while True bytecode (optimized):")
dis.dis(infinite_pattern)
print("\nwhile x bytecode (not optimized):")
dis.dis(conditional_pattern)

# while True compiles to a simple unconditional jump
# while x compiles to a load + test + conditional jump

CPython optimizes 'while True' into an unconditional jump — there is no condition check at all. 'while variable' adds a load and test on every iteration.

Want to try these examples interactively?

Open Expert Playground