Loops

For Loops

Basic Syntax

for <temporary_variable> in <collection>:
    <action>

# Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

range()

range(n) generates numbers from 0 to n-1.

for i in range(6):
    print(i)  # Prints numbers 0 to 5

You can also use: range(start, stop, step) for example, range(2, 10, 2) → 2, 4, 6, 8

Ignoring the Loop Variable

Use _ when the variable won't be used inside the loop.

for _ in range(3):
    print("Do this 3 times")

While Loops

Basic Syntax

while <condition>:
    <action>

# Example:
count = 0
while count < 3:
    print(count)
    count += 1

Looping Through a List

my_list = ['a', 'b', 'c']
index = 0

while index < len(my_list):
    print(my_list[index])
    index += 1

User Controlled While Loop

To quit a program with input:

message = ""
while message != "quit":
    message = input("Type something (or 'quit'): ")
    if message != "quit":
        print(message)

Loop Controls

break - exit the loop immediately

for num in range(10):
    if num == 5:
        break
    print(num)

continue - skip the current iteration

for num in range(5):
    if num == 2:
        continue
    print(num)  # Skips 2

pass - placeholder that does nothing

for _ in range(3):
    pass  # Can be used to define empty loop or function blocks

Flags

Flags are useful when multiple conditions control whether a loop runs. Use a flag when:

  • You may exit the loop for more than one reason
  • You're writing larger programs with more conditions
flag = True
while flag:
    message = input("Say something (or 'quit'): ")

    if message == 'quit':
        flag = False
    else:
        print(message)