Skillversitas

Loops

Jython supports the two Python loop forms - for (iteration) and while (condition-based) - plus the standard loop controls break, continue, and the else clause. Range-based loops, list comprehensions, and iteration over Java collections all work.

for with range

for i in range(5):
    print(i, i * i)

for i in range(2, 10, 2):
    print(i)  # 2 4 6 8

for over Iterables

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

for key, value in {"a": 1, "b": 2}.items():
    print(key, value)

# enumerate for index + value
for i, fruit in enumerate(fruits):
    print(i, fruit)

while Loops

n = 1
while n < 100:
    n *= 2
print(n)  # 128

break, continue, else

for x in range(10):
    if x % 2 == 0:
        continue      # skip evens
    if x > 5:
        break         # stop at 7
    print(x)          # 1 3 5

for x in range(5):
    pass
else:
    print("loop finished without break")  # runs

List Comprehensions

squares = [x * x for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
print(squares[:5], len(evens))

Iterating Java Collections

import java.util

al = java.util.ArrayList()
al.add("x")
al.add("y")

for item in al:          # Jython iterates java.util collections
    print(item)

mp = java.util.HashMap()
mp.put("a", 1)
mp.put("b", 2)
for k in mp.keySet():
    print(k, mp.get(k))

Nested Loops

for i in range(3):
    for j in range(3):
        if i == j:
            continue
        print(i, j)
# pairs off the diagonal

Summary

Loops in Jython are standard Python: for with range or any iterable, while for condition loops, break/continue/else for control, and comprehensions for compact construction. Java collections (ArrayList, HashMap) are directly iterable, so the same loop idioms work over Java data structures.