Control Flow Examples


Control Flow Examples

This document introduces while, for loops and list comprehensions.

Module Introduction

Supports while True, for with return/break, list comprehensions, etc. Built-in examples:

#!pika
i = 0
while i < 3:
    i += 1
print(i)
#!pika
#!pika
a = [x for x in range(5)]
assert len(a) == 5
#!pika

Example Code

while Loop (while_true.py)

#!pika
i = 0
while True:
    i += 1
    print(i)
#!pika

Note: Infinite loop that prints incrementing i each time. In actual use, combine with break or conditional exit.

for with return/break (for_return.py)

#!pika
def test1():
    for i in range(10):
        if i == 3:
            return

def test2():
    for i in range(10):
        if i == 3:
            break

test1()
test2()
gcdump()
#!pika

Note: test1 returns from function when i==3; test2 breaks out of loop when i==3. gcdump() is for memory debugging (if environment supports).

List Comprehension (comprehension.py)

#!pika
a = [i for i in range(10)]
assert len(a) == 10

for i in range(10):
    q = [x for x in range(i)]
    assert len(q) == i

print('PASS')
#!pika

Note: [i for i in range(10)] generates a list of 0-9; inner loop validates comprehensions of different lengths.

Notes

  • while True must have exit conditions to avoid infinite loops that consume device resources.
  • List comprehensions allocate entire lists at once, watch memory usage with large ranges.