GitHub

Loops

Stable Loop syntax is stable in Levython 1.0.

Levython provides for and while loops for iteration. All loops use curly braces { } for blocks.

For Loop with Range#

Iterate over a range of numbers using range(start, end):

for variable in range(start, end) { body }
levython
# Count from 1 to 5
for i in range(1, 6) {
    say(str(i))
}
# Output: 1, 2, 3, 4, 5

# Sum numbers 1 to 10
total <- 0
for n in range(1, 11) {
    total <- total + n
}
say("Sum: " + str(total))  # Sum: 55
Note: The range(start, end) function generates numbers from start up to but not including end.

For Loop over Lists#

Iterate directly over list elements:

for element in list { body }
levython
# Iterate over strings
colors <- ["red", "green", "blue"]
for color in colors {
    say("Color: " + color)
}
# Output:
# Color: red
# Color: green
# Color: blue

# Iterate over numbers
prices <- [10, 25, 15, 30]
total <- 0
for price in prices {
    total <- total + price
}
say("Total: " + str(total))  # Total: 80

While Loop#

Execute a block while a condition is true:

while condition { body }
levython
# Countdown
n <- 5
while n > 0 {
    say(str(n))
    n <- n - 1
}
say("Liftoff!")
# Output: 5, 4, 3, 2, 1, Liftoff!

# Find first power of 2 >= 100
power <- 1
while power < 100 {
    power <- power * 2
}
say("First power of 2 >= 100: " + str(power))  # 128
Warning: Be careful to update your loop variable to avoid infinite loops!

Break and Continue#

Control loop execution with break (exit loop) and continue (skip to next iteration):

Break Statement

The break statement immediately exits the innermost loop:

levython
# Find first even number greater than 10
numbers <- [3, 7, 12, 15, 18, 21]
for num in numbers {
    if num > 10 and num % 2 == 0 {
        say("Found: " + str(num))
        break  # Exit loop immediately
    }
}
# Output: Found: 12

# Search with break
items <- ["apple", "banana", "cherry", "date"]
target <- "cherry"
found <- false

for item in items {
    if item == target {
        say("Found " + target + "!")
        found <- true
        break
    }
}

if not found {
    say(target + " not found")
}

Continue Statement

The continue statement skips the rest of the current iteration and moves to the next:

levython
# Print only odd numbers
for i in range(1, 11) {
    if i % 2 == 0 {
        continue  # Skip even numbers
    }
    say(str(i))
}
# Output: 1, 3, 5, 7, 9

# Process valid entries only
values <- [10, -5, 0, 15, -3, 20]
sum <- 0

for val in values {
    if val <= 0 {
        continue  # Skip non-positive values
    }
    sum <- sum + val
}
say("Sum of positive values: " + str(sum))  # 45
Note: In nested loops, break and continue only affect the innermost loop they appear in.

Nested Loops#

Loops can be nested inside each other for multi-dimensional iteration:

levython
# Multiplication table
for i in range(1, 4) {
    for j in range(1, 4) {
        result <- i * j
        say(str(i) + " x " + str(j) + " = " + str(result))
    }
}
# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
# 2 x 1 = 2
# 2 x 2 = 4
# ... and so on

# 2D grid traversal
grid <- [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in grid {
    for cell in row {
        say(str(cell))
    }
}

Common Patterns#

Building Lists

levython
# Pattern: Building a list
squares <- []
for i in range(1, 6) {
    append(squares, i * i)
}
say(str(squares))  # [1, 4, 9, 16, 25]

# Pattern: Filter and collect
numbers <- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens <- []
for n in numbers {
    if n % 2 == 0 {
        append(evens, n)
    }
}
say(str(evens))  # [2, 4, 6, 8, 10]

Accumulation

levython
# Pattern: Sum accumulation
numbers <- [10, 20, 30, 40, 50]
total <- 0
for n in numbers {
    total <- total + n
}
say("Total: " + str(total))  # Total: 150

# Pattern: Product accumulation
values <- [2, 3, 4, 5]
product <- 1
for val in values {
    product <- product * val
}
say("Product: " + str(product))  # Product: 120

Search and Find

levython
# Pattern: Finding an element
numbers <- [3, 7, 2, 9, 5]
target <- 9
found <- false
for n in numbers {
    if n == target {
        found <- true
        break
    }
}
say("Found: " + str(found))  # Found: true

# Pattern: Finding index
items <- ["apple", "banana", "cherry"]
search <- "banana"
index <- -1
i <- 0
for item in items {
    if item == search {
        index <- i
        break
    }
    i <- i + 1
}
say("Index: " + str(index))  # Index: 1

Transformation

levython
# Pattern: Map transformation
temps_celsius <- [0, 10, 20, 30, 40]
temps_fahrenheit <- []
for c in temps_celsius {
    f <- (c * 9 / 5) + 32
    append(temps_fahrenheit, f)
}
say(str(temps_fahrenheit))  # [32, 50, 68, 86, 104]

# Pattern: String building
words <- ["Hello", "World", "from", "Levython"]
sentence <- ""
for word in words {
    if sentence != "" {
        sentence <- sentence + " "
    }
    sentence <- sentence + word
}
say(sentence)  # Hello World from Levython

Performance Optimization#

Levython's JIT compiler optimizes loop performance automatically:

Loop Optimization Techniques

  • Range Loop Optimization: Simple summation loops are compiled to tight native code
  • Inlined Operations: Arithmetic inside loops uses direct x86-64 instructions
  • List Iteration: Direct memory access without bounds checking overhead in hot paths
  • Loop Unrolling: The JIT may unroll small loops for better instruction pipelining
levython
# This loop is JIT-optimized for maximum performance
total <- 0
for i in range(0, 1000000) {
    total <- total + i
}
# Executes in milliseconds with native x86-64 code

# Complex loop - still very fast
sum_squares <- 0
for i in range(1, 10001) {
    sum_squares <- sum_squares + (i * i)
}
say("Sum of squares 1-10000: " + str(sum_squares))
Performance Tip: Levython's FastVM with computed-goto dispatch and JIT compilation makes loops extremely fast. For computational workloads, Levython loops approach C-level performance after JIT warm-up (~3 iterations).