Live
Auto strategy optimizer — AI improves your edge while you sleep
guidebeginner18 min

Loops: Repeating Actions

Use for and while loops to repeat code without writing it multiple times.

Last updated: Jan 28, 2026

Loops let you repeat code. Instead of writing the same thing 100 times, you write it once and tell Python how many times to repeat it.

The for Loop

A for loop repeats code for each item in a sequence:

python
# Print numbers 0 through 4
for i in range(5):
    print(i)

Output:

text
0
1
2
3
4

range(5) generates numbers 0, 1, 2, 3, 4 (five numbers, starting from 0). The variable i takes each value in turn.

range() Options

python
# range(stop) - 0 to stop-1
for i in range(3):
    print(i)  # 0, 1, 2

# range(start, stop) - start to stop-1
for i in range(2, 5):
    print(i)  # 2, 3, 4

# range(start, stop, step) - with custom increment
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

# Counting backwards
for i in range(5, 0, -1):
    print(i)  # 5, 4, 3, 2, 1

Looping Over Lists

You can loop directly over items in a list:

python
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I like {fruit}")

Output:

text
I like apple
I like banana
I like cherry

Looping Over Strings

python
word = "Python"

for letter in word:
    print(letter)

Output: P, y, t, h, o, n (each on its own line)

The while Loop

A while loop repeats as long as a condition is True:

python
count = 0

while count < 5:
    print(count)
    count += 1  # Don't forget this or it loops forever!

print("Done!")

Output: 0, 1, 2, 3, 4, Done!

break and continue

break exits the loop immediately. continue skips to the next iteration:

python
# break - exit the loop early
for i in range(10):
    if i == 5:
        break  # Stop when we hit 5
    print(i)  # Prints 0, 1, 2, 3, 4

# continue - skip this iteration
for i in range(5):
    if i == 2:
        continue  # Skip 2
    print(i)  # Prints 0, 1, 3, 4

Practical Example: Sum and Average

python
numbers = [10, 20, 30, 40, 50]

total = 0
for num in numbers:
    total += num

average = total / len(numbers)
print(f"Sum: {total}")       # Sum: 150
print(f"Average: {average}") # Average: 30.0

Nested Loops

Loops inside loops:

python
# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}")
    print("---")  # Separator after each row

Practice

  1. Print all even numbers from 1 to 20
  2. Calculate the factorial of a number (5! = 5 * 4 * 3 * 2 * 1)
  3. Print a countdown from 10 to 1, then print "Liftoff!"
  4. Find the largest number in a list without using max()
  5. Print a triangle of stars (first row has 1, second has 2, etc.)

Tags

loopsforwhileiterationcontrol-flow
Related documentation