Loops and Iteration

Loops and Iteration

For Loops and While Loops

In this lesson, you’ll learn the core loop constructs in Python, including for and while loops, and common control-flow patterns like break, continue, and pass. By the end, you should be able to iterate over sequences, implement simple menus, and validate user input. If you’re new to Python, you may want to start with Introduction to Python first, then return here to apply looping concepts. For broader control flow discussions, see Control Flow. For data-centric topics, explore Data Structures and Working with Strings as you implement examples.

Note: If you’re brushing up on variables and types, see Variables for quick references on naming conventions and data types.

1. For Loops

Purpose:

Used to iterate over a sequence (like a list, string, tuple, range, etc.).

Syntax:

for variable in iterable:
# code block

Example 1: Looping through a list

fruits = [“apple”, “banana”, “cherry”]

for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

Example 2: Using range()

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

Output:

0
1
2
3
4

range(n) gives numbers from 0 to n-1

You can also use:

range(start, stop, step)

Example 3: Loop with index (using enumerate())

colors = [“red”, “green”, “blue”]

for index, color in enumerate(colors):
print(f”{index}: {color}”)

When to use for:

  • You know how many times to loop
  • You’re iterating over a list, string, or range
  • You want clean, readable iteration

Tip: If you’re new to Python, start with Introduction to Python to understand the basics of variables and control flow, and then come back to practice loops. For broader control-flow concepts, see Control Flow.

2. While Loops

Purpose:

Repeats a block of code as long as a condition is True.

Syntax:

while condition:
# code block

Example 1: Basic while loop

count = 0

while count < 5:
print(“Count is:”, count)
count += 1

Example 2: User input loop

password = “”

while password != “secret”:
password = input(“Enter the password: “)

print(“Access granted.”)

When to use while:

  • You don’t know in advance how many times to loop
  • You’re waiting for a condition to be met
  • Great for input validation, menus, waiting for user action, etc.

Control Flow Keywords (work in both loops)

Keyword Use
break Exits the loop immediately
continue Skips remaining code in current iteration and moves to next iteration
else Optional block that executes only if loop completes normally (without break)

break Example:

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

continue Example:

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

Summary: for vs while

Feature for Loop while Loop
Iterates over Sequence (range, list, string) Until a condition becomes False
Use when You know how many iterations needed You don’t know how many iterations needed
Example Use Printing list items, counting Waiting for correct user input

Want More?

I can add:

  • Loop exercises (countdown timer, sum calculator, etc.)
  • A quiz or worksheet
  • A visual loop flowchart
  • Let me know what format you’d like next!

Break, Continue, and Pass

1. break – Exit the loop early

What it does:

Immediately terminates the nearest enclosing loop — either for or while.

Syntax:

for item in iterable:
if condition:
break

Example:

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

Output:

0
1
2
3
4

The loop stops before 5, because break exits the loop.

Real Use Case:

  • Exiting on a condition (e.g. stop searching when found)
  • Validating passwords or attempts

2. Continue – Skip this iteration

What it does:

Skips the rest of the code in the current loop iteration, and moves to the next one.

Syntax:

for item in iterable:
if condition:
continue
# code here will be skipped if condition is True

Example:

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

Output:

0
1
3
4

When num == 2, it skips the print() and goes to the next loop.

Real Use Case:

  • Skipping invalid data
  • Ignoring certain values (e.g., skip vowels or zeroes)

3. pass – Do nothing (placeholder)

What it does:

Literally does nothing — used when a statement is syntactically required but you don’t want any code to run.

Syntax:

if condition:
pass # Do nothing (for now)

Example:

for num in range(3):
if num == 1:
pass
print(f”Number is {num}”)

Output:

Number is 0
Number is 1
Number is 2

The pass does nothing — but it lets the if statement exist without error.

Real Use Case:

  • Placeholder for code you’ll write later
  • Empty function or class definitions
  • Keeping structure while under development

Summary Table:

Keyword Purpose Ends Loop? Skips Iteration? Use Case
break Exits loop immediately X Stop a loop early (e.g., on match)
continue Skips rest of current iteration X Skip unwanted data
pass Does nothing; placeholder X X Keep syntax valid without logic

Bonus Practice Ideas:

  • Loop through numbers and break when divisible by 7
  • Skip even numbers using continue
  • Create an empty function using pass

Looping through strings, lists, and ranges

You can use for loops to iterate over sequences in Python — like strings, lists, and ranges — because they’re all iterables.

1. Looping Through a String

Purpose:

Each character in a string can be accessed one by one.

Syntax:

for char in string:
# do something with char

Example:

word = “Python”

for letter in word:
print(letter)

Output:

P
y
t
h
o
n

Use Cases:

  • Counting vowels
  • Reversing or analyzing text
  • String transformations

For more string-related operations, see Working with Strings.

2. Looping Through a List

Purpose:

Iterate through each item (element) in a list.

Syntax:

for item in list_name:
# do something with item

Example:

colors = [“red”, “green”, “blue”]

for color in colors:
print(color.upper())

Output:

RED
GREEN
BLUE

Looping with enumerate():

for index, color in enumerate(colors):
print(f”{index}: {color}”)

Use Cases:

  • Displaying indexed menus
  • Searching or filtering
  • Data transformation

To learn more about lists and data structures, see Data Structures.

3. Looping Through a Range

Purpose:

Use range() to generate a sequence of numbers, which can be used for indexed loops or counters.

Syntax:

for i in range(stop)
for i in range(start, stop)
for i in range(start, stop, step)

Example 1: Basic Range

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

Output:

0
1
2
3
4

Example 2: Start and Stop

for i in range(2, 6):
print(i)

Output:

2
3
4
5

Example 3: With Step

for i in range(0, 10, 2):
print(i)

Output:

0
2
4
6
8

Use Cases:

Use range() for simple counters, indexing, and to drive loops where the number of iterations is known ahead of time.

Looking for broader loop concepts? See Loops and Iteration.

Scroll to Top