Loops: Beginner

Waymo's self-driving data pipeline processes raw LiDAR point clouds and camera frames using Python preprocessing scripts that iterate over thousands of sensor readings per second. Waymo engineers have documented how every mile logged by the fleet generates labeled training data that Python loops process to improve the perception models continuously. The for loops and while loops you are about to write are the same iteration constructs powering that kind of large-scale sensor data processing.

Iterating with for Loops

Daily Life
Interviews

Loop through any list or string

A for loop repeats a block of code once for each item in a sequence. Without one, processing fifty files means writing fifty nearly-identical blocks of code. A loop collapses all of that into three lines.
THE CASE OF THE TRIPLE PRINT

Maria Santos filed a sprint blocker at 8:47 AM. Her intern wrote a four-line script. One print statement in the code, three lines on the console. Alex Park reviewed the code and signed off. Now Maria wants answers before the stakeholder review.

One list. Three names. One variable that keeps changing.

variables
variablevalue
names['Alice', 'Bob', 'Charlie']
name(changes each iteration)
iterations
iterationname valueoutput
1AliceWelcome, Alice
2BobWelcome, Bob
3CharlieWelcome, Charlie

The for loop iterates over each item in a sequence (like a list, string, or tuple) one at a time. On each iteration, the loop variable is assigned the next item from the sequence, and the loop body executes with that value.

Basic for Loop Syntax

A for loop has the form: for variable in sequence: followed by an indented block. The variable takes on each value from the sequence in order:

1fruits = ["apple", "banana", "cherry"]
2
3for fruit in fruits:
4 print("I like", fruit)
5
6print("Done!")
>>>Output
I like apple
I like banana
I like cherry
Done!

The loop executes three times. On the first iteration, fruit is "apple". On the second, it is "banana". On the third, "cherry". After all items are processed, the loop ends and execution continues with the next unindented statement.

Looping Over Strings

Strings are sequences of characters, so you can loop over them character by character:
1word = "Python"
2
3for char in word:
4 print(char)
>>>Output
P
y
t
h
o
n
Each character in the string becomes the loop variable in turn. This is useful for analyzing text character by character.

Accumulating Results

A common pattern is to build up a result as you loop through items. Initialize an accumulator before the loop, then update it inside:
1numbers = [10, 20, 30, 40, 50]
2
3# Calculate the sum
4total = 0
5for num in numbers:
6 total = total + num
7
8print("Sum:", total)
9
10count = 0
11for num in numbers:
12 if num > 25:
13 count = count + 1
14
15print("Numbers > 25:", count)
>>>Output
Sum: 150
Numbers > 25: 3
TIP
While sum() and len() are built-in, understanding the accumulator pattern is essential. Many real-world calculations require custom accumulation logic that built-in functions cannot handle.

Building New Lists

You can create new lists by looping through existing ones and appending transformed items:
1names = ["alice", "bob", "charlie"]
2
3# Create a list of uppercase names
4upper_names = []
5for name in names:
6 upper_names.append(name.upper())
7
8print(upper_names)
9
10# Filter a list
11numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12
13evens = []
14for n in numbers:
15 if n % 2 == 0:
16 evens.append(n)
17
18print(evens)
>>>Output
['ALICE', 'BOB', 'CHARLIE']
[2, 4, 6, 8, 10]
This pattern of initializing an empty list before the loop and appending items inside is called the accumulator pattern for lists. It is one of the most common patterns in Python programming.
Test your understanding of the accumulator pattern. Choose the right operator in each blank to produce different results:
Fill in the Blank

> A loop adds up numbers using an accumulator variable. Pick the operator to see how the running total changes.

total = 0
for n in [1, 2, 3]:
    total  n
print(total)

Looping Multiple Data Types

For loops work with any iterable object in Python. Beyond lists and strings, you can iterate over tuples, sets, dictionary keys, and more. The loop automatically handles extracting each element regardless of the underlying data structure:
1# Looping over a tuple
2coordinates = (10, 20, 30)
3for coord in coordinates:
4 print("Coordinate:", coord)
5
6print("---")
7
8# Looping over a set (order may vary)
9unique_items = {"apple", "banana", "cherry"}
10for item in unique_items:
11 print("Item:", item)
12
13print("---")
14
15# Looping over dictionary keys
16scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
17for name in scores:
18 print(name, "scored", scores[name])
>>>Output
Coordinate: 10
Coordinate: 20
Coordinate: 30
---
Item: cherry
Item: apple
Item: banana
---
Alice scored 95
Bob scored 87
Charlie scored 92

Finding Values in Lists

A common use case for loops is searching for a specific value or finding values that match criteria. You can combine loops with conditionals to locate items:
1# Find the first even number
2numbers = [7, 3, 9, 4, 1, 8]
3first_even = None
4
5for num in numbers:
6 if num % 2 == 0:
7 first_even = num
8 break
9
10print("First even:", first_even)
11
12# Find the maximum value manually
13values = [23, 67, 45, 89, 12, 56]
14maximum = values[0]
15
16for val in values:
17 if val > maximum:
18 maximum = val
19
20print("Maximum:", maximum)
21
22# Find all values above threshold
23threshold = 50
24above = []
25for val in values:
26 if val > threshold:
27 above.append(val)
28
29print("Above 50:", above)
>>>Output
First even: 4
Maximum: 89
Above 50: [67, 89, 56]
TIP
While Python has built-in functions like max(), min(), and list comprehensions that can do these tasks more concisely, understanding the loop-based approach is essential for more complex searches that built-ins cannot handle.

range() Function

Daily Life
Interviews

Generate number sequences with range()

The range() function generates a sequence of numbers. It is commonly used with for loops when you need to repeat an action a specific number of times or iterate over a sequence of integers.

range() with One Argument

range(n) generates numbers from 0 up to (but not including) n. This gives you exactly n iterations:

1# Print 0 to 4
2for i in range(5):
3 print(i)
>>>Output
0
1
2
3
4

Notice that range(5) produces 0, 1, 2, 3, 4 - five numbers starting from 0, not including 5. This is consistent with zero-based indexing.

range() with Two Arguments

range(start, stop) generates numbers from start up to (but not including) stop:

1# Print 5 to 9
2for i in range(5, 10):
3 print(i)
4
5print("---")
6
7# Print 1 to 5
8for i in range(1, 6):
9 print(i)
>>>Output
5
6
7
8
9
---
1
2
3
4
5

range() with Three Args

range(start, stop, step) lets you specify the increment between numbers:

1# Count by 2s
2for i in range(0, 10, 2):
3 print(i)
4
5print("---")
6
7# Count by 5s
8for i in range(0, 26, 5):
9 print(i)
10
11print("---")
12
13# Count backwards
14for i in range(10, 0, -1):
15 print(i)
>>>Output
0
2
4
6
8
---
0
5
10
15
20
25
---
10
9
8
7
6
5
4
3
2
1

Each form of range() gives you a different level of control over the generated sequence. Here are the three signatures and their behavior at a glance:

range(n)range(a, b)range(a,b,s)range(n,0,-1)
range(n)
Count from zero
Generates 0 up to n minus 1
range(a, b)
Custom start
Starts at a, ends before b
range(a,b,s)
With step
Increments by s each time
range(n,0,-1)
Count backward
Negative step reverses it

range() for Index Access

Sometimes you need both the index and the value. You can use range with len to loop by index:

1colors = ["red", "green", "blue"]
2
3# Access by index
4for i in range(len(colors)):
5 print("Index", i, "=", colors[i])
6
7print("---")
8
9# Modify list in place
10numbers = [1, 2, 3, 4, 5]
11for i in range(len(numbers)):
12 numbers[i] = numbers[i] * 2
13
14print(numbers)
>>>Output
Index 0 = red
Index 1 = green
Index 2 = blue
---
[2, 4, 6, 8, 10]

Using range(len(list)) for index access works, but Python has a better way: enumerate(). You will learn this in the intermediate lesson. For now, range(len()) is fine.

Sequences from range()

The range function is not limited to controlling loops. You can convert a range to a list to create numeric sequences for various purposes:

1# Create a list of numbers
2numbers = list(range(1, 11))
3print("1 to 10:", numbers)
4
5# Create even numbers
6evens = list(range(2, 21, 2))
7print("Even 2-20:", evens)
8
9# Create a countdown list
10countdown = list(range(10, 0, -1))
11print("Countdown:", countdown)
12
13# Useful for creating indices
14indices = list(range(5))
15print("Indices:", indices)
>>>Output
1 to 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even 2-20: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Countdown: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Indices: [0, 1, 2, 3, 4]

The list() function converts the range object into an actual list. This is useful when you need to store the sequence or pass it to a function that requires a list rather than an iterator.

Repeating Actions N Times

Sometimes you just need to repeat an action a specific number of times without caring about the loop variable. By convention, you can use an underscore for variables you do not intend to use:
1# Print a separator line 3 times
2for _ in range(3):
3 print("-" * 20)
4
5print()
6
7# Collect user ratings (simulated)
8ratings = []
9for _ in range(5):
10 ratings.append(4)
11
12print("Collected ratings:", ratings)
13print("Average:", sum(ratings) / len(ratings))
>>>Output
--------------------
--------------------
--------------------
 
Collected ratings: [4, 4, 4, 4, 4]
Average: 4.0
Python Quiz

> Generate a sequence of integers starting at 2 and stopping before 8. Pick the built-in that produces the number sequence, and the one that counts how many numbers were generated.

nums = list(___(2, 8))
print(nums[0])
print(___(nums))
range
tuple
list
sum
len

range() is memory efficient: it does not store all the numbers at once. It generates each value on demand, making it safe to use with very large ranges like range(1_000_000) without consuming extra memory.

The three-argument form range(start, stop, step) covers almost every numeric sequence you will need in a for loop, including counting up, counting down, and selecting every nth value.

When you need the actual list of numbers for slicing, indexing, or repeated access, wrap range() in list(). Otherwise, iterating over the range object directly in a for loop is the preferred approach.

Loops with while

Daily Life
Interviews

Repeat actions until a condition fails

A while loop repeats as long as its condition is True. Unlike for loops that iterate a fixed number of times, while loops continue until the condition becomes False. This makes them ideal when you do not know in advance how many iterations you need.

Basic while Syntax

A while loop has the form: while condition: followed by an indented block. The condition is checked before each iteration:

1count = 0
2
3while count < 5:
4 print("Count is", count)
5 count = count + 1
6
7print("Loop finished!")
>>>Output
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Loop finished!
The loop checks the condition, executes the body if True, then checks again. When count reaches 5, the condition becomes False and the loop ends. Here is the execution model step by step:
01
Evaluate condition
Python checks whether the while condition is True or False
02
Run loop body
If True, execute all indented statements inside the loop
03
Update state
The loop body should change something that affects the condition
04
Repeat or exit
Jump back to step 1. If condition is False, skip to code after the loop

Comparing while and for

Choose the right loop type based on your situation:
Use for When
  • Iterating over a sequence
  • You know how many times to loop
  • Processing each item in a collection
  • Using range() for a count
Use while When
  • Unknown number of iterations
  • Waiting for a condition
  • User input loops
  • Reading until end of data
When deciding which loop type to use, keep these practical rules in mind. They cover the most common scenarios you will encounter in real code.
Quick Decision Guide for Loop Type
  • Processing every item in a list, string, or file: use a for loop.
  • Repeating an action a known number of times: use for with range().
  • Waiting for user input or an external condition: use a while loop.
  • Polling or retrying until success or timeout: use while with a counter.

Common while Patterns

Here are typical use cases for while loops:
1# Countdown
2n = 3
3while n > 0:
4 print(n)
5 n = n - 1
6print("Liftoff!")
7
8print("---")
9
10# Find first match
11items = ["a", "b", "c", "target", "d"]
12i = 0
13while i < len(items) and items[i] != "target":
14 i = i + 1
15print("Found at index:", i)
16
17print("---")
18
19# Process until empty
20queue = [1, 2, 3]
21while queue:
22 item = queue.pop(0)
23 print("Processing:", item)
24print("Queue empty")
>>>Output
3
2
1
Liftoff!
---
Found at index: 3
---
Processing: 1
Processing: 2
Processing: 3
Queue empty

Avoiding Infinite Loops

A while loop that never ends is called an infinite loop. This happens when the condition never becomes False. Always ensure something in the loop body moves toward ending the loop:
1# CORRECT: count increases, eventually >= 3
2count = 0
3while count < 3:
4 print(count)
5 count = count + 1
6
7# WOULD BE WRONG (don't run this!):
8# while True: # Never ends!
9# print("Forever...")
10
11# WOULD BE WRONG:
12# x = 0
13# while x < 10:
14# print(x)
15# # Forgot to increment x!
>>>Output
0
1
2
Can you spot the bug? This while loop has a subtle error that would cause it to run forever. Remove the problematic tile to fix it:
Debug Challenge

> This while loop should print 0 through 4, but it runs forever. Find the tile that prevents the counter from advancing.

LogicError: count never changes, loop runs forever

Infinite Loops: while True

A common pattern is to use while True combined with break to create loops that exit based on complex conditions. This is especially useful when the exit condition is checked in the middle of the loop body rather than at the beginning:

1# Simulate reading until valid input
2attempts = 0
3max_attempts = 3
4valid_inputs = ["yes", "no"]
5test_inputs = ["maybe", "perhaps", "yes"]
6
7result = None
8while True:
9 if attempts >= max_attempts:
10 print("Max attempts reached")
11 break
12
13 # Simulate getting input
14 user_input = test_inputs[attempts]
15 print("Attempt", attempts + 1, "- Got:", user_input)
16 attempts += 1
17
18 if user_input in valid_inputs:
19 result = user_input
20 print("Valid input received!")
21 break
22
23print("Final result:", result)
>>>Output
Attempt 1 - Got: maybe
Attempt 2 - Got: perhaps
Attempt 3 - Got: yes
Valid input received!
Final result: yes
TIP
The while True pattern gives you full control over exactly when the loop exits. Just make sure every possible code path eventually reaches a break statement, or includes logic to prevent infinite execution.

Simulating Do-While Loops

Python does not have a do-while loop like some languages, but you can simulate one. A do-while loop executes the body at least once before checking the condition. You can achieve this with while True and break:
1count = 5
2
3# This regular while would never run
4# while count < 5:
5# print("Regular while:", count)
6
7# Simulated do-while runs at least once
8count = 5
9while True:
10 print("Do-while style:", count)
11 count += 1
12 if count >= 7:
13 break
14
15print("Done!")
>>>Output
Do-while style: 5
Do-while style: 6
Done!
This pattern guarantees the loop body runs at least once because the condition check happens after the body executes, not before.

Using break and continue

Daily Life
Interviews

Exit or skip iterations on demand

Python provides two statements to control loop execution: break exits the loop immediately, and continue skips the rest of the current iteration and moves to the next one.

The break Statement

break immediately terminates the innermost loop. Execution continues with the first statement after the loop:

1# Find first negative number
2numbers = [1, 5, 3, -2, 7, 8]
3
4for num in numbers:
5 if num < 0:
6 print("Found negative:", num)
7 break
8 print("Checked:", num)
9
10print("Search complete")
>>>Output
Checked: 1
Checked: 5
Checked: 3
Found negative: -2
Search complete

When the loop finds -2, break executes and the loop ends immediately. The remaining items (7, 8) are never checked.

The continue Statement

continue skips the rest of the current iteration and jumps to the next iteration of the loop:

1# Print only positive numbers
2numbers = [1, -2, 3, -4, 5]
3
4for num in numbers:
5 if num < 0:
6 continue
7 print(num)
8
9print("Done")
>>>Output
1
3
5
Done

When continue executes, the loop immediately moves to the next item. The print statement after continue is skipped for negative numbers.

break vs continue

Understanding the difference is crucial:
break
  • Exits the loop entirely
  • Loop body never runs again
  • Continues after the loop
  • Use for early termination
continue
  • Skips current iteration only
  • Loop continues with next item
  • Loop may run many more times
  • Use to skip certain items

break and continue in while

These statements work the same way in while loops:
1# Process until sentinel value
2# -1 is the sentinel value
3data = [10, 20, -1, 30, 40]
4i = 0
5total = 0
6
7while i < len(data):
8 if data[i] == -1:
9 break
10 total = total + data[i]
11 i = i + 1
12
13print("Total before sentinel:", total)
14
15print("---")
16
17# Skip processing errors
18values = [5, 0, 3, 0, 2]
19i = 0
20results = []
21
22while i < len(values):
23 val = values[i]
24 i = i + 1
25 if val == 0:
26 continue
27 results.append(10 / val)
28
29print("Results:", results)
>>>Output
Total before sentinel: 30
---
Results: [2.0, 3.3333333333333335, 5.0]
TIP
In while loops, make sure to update the loop variable before continue, or you may create an infinite loop. The continue skips everything after it, including the increment.

Combining break with Flags

Sometimes you need to know whether a loop exited normally or via break. A flag variable can track this distinction:
1# Search with a found flag
2numbers = [1, 3, 5, 7, 9, 11]
3target = 7
4found = False
5
6for num in numbers:
7 if num == target:
8 found = True
9 break
10
11if found:
12 print("Found", target, "in the list!")
13else:
14 print(target, "not found")
15
16# Same search, target not present
17target = 8
18found = False
19for num in numbers:
20 if num == target:
21 found = True
22 break
23
24if found:
25 print("Found", target)
26else:
27 print(target, "not found")
>>>Output
Found 7 in the list!
8 not found
The flag variable starts False and becomes True only if the target is found. After the loop, you check the flag to determine the outcome. This pattern is useful when you need different behavior based on whether the search succeeded.

Nested Loops and break

The break statement only exits the innermost loop. If you have nested loops and want to exit the outer loop, you need additional logic like a flag variable:

1# break only exits inner loop
2for i in range(3):
3 for j in range(3):
4 if j == 1:
5 break
6 print("i =", i, "j =", j)
7 print("Outer loop continues, i =", i)
8
9print("---")
10
11# Use a flag for outer loop
12found = False
13for i in range(3):
14 if found:
15 break
16 for j in range(3):
17 print("Checking:", i, j)
18 if i == 1 and j == 1:
19 found = True
20 break
21
22print("Stopped at i=1, j=1")
>>>Output
i = 0 j = 0
Outer loop continues, i = 0
i = 1 j = 0
Outer loop continues, i = 1
i = 2 j = 0
Outer loop continues, i = 2
---
Checking: 0 0
Checking: 0 1
Checking: 0 2
Checking: 1 0
Checking: 1 1
Stopped at i=1, j=1

Knowing when to use break versus continue prevents subtle bugs and keeps loop logic readable. Follow these guidelines:

Do
  • Use break for early exit on first match
  • Use continue to skip invalid items
  • Update counter before continue in while
  • Use flags to exit outer loops
Don't
  • Use break when you need all matches
  • Nest continue inside complex conditions
  • Forget counter update causes infinite loop
  • Assume break exits all nested loops
Python Quiz

> Collect the first 3 odd numbers from a range. Pick the keyword that skips even numbers, and the one that stops the loop once 3 odds are found.

result = []
for n in range(10):
    if n % 2 == 0:
        ___
    result.append(n)
    if len(result) == 3:
        ___
print(result)
break
continue
pass
return

break and continue are most valuable when processing input that has mixed valid and invalid entries. Use continue to skip bad records and break to stop as soon as a target is found.

A common pattern in searching is to use break when a match is found and rely on a flag variable or else clause to detect when no match was found after the full loop completes.

In while loops, forgetting to update the loop counter before a continue statement is a frequent cause of infinite loops. Always ensure the condition can eventually become False regardless of which path through the loop body is taken.

Loop Variable Scope

Daily Life
Interviews

Predict variable values after loops end

In Python, loop variables (the variable after for or used in a while condition) remain accessible after the loop ends. This is different from some other languages where loop variables are scoped only to the loop body.

Loop Variables Persist

After a for loop completes, the loop variable retains its last value:

1for i in range(5):
2 pass
3
4print("After loop, i =", i)
5
6for letter in "ABC":
7 pass
8
9print("After loop, letter =", letter)
10
11items = ["a", "b", "target", "c"]
12for i, item in enumerate(items):
13 if item == "target":
14 break
15
16print("Found target at index:", i)
>>>Output
After loop, i = 4
After loop, letter = C
Found target at index: 2

After the loop, i holds the last value it was assigned, which is 4 (the last number in range(5)). For letters, it holds "C".

Empty Loops: Undefined Vars

If a loop never executes (empty sequence), the loop variable is never assigned:
1# This loop never runs
2empty_list = []
3for item in empty_list:
4 print(item)
5
6# item is undefined here
7# print(item) # NameError!
8
9result = None
10for x in empty_list:
11 result = x
12
13if result is None:
14 print("List was empty")
15else:
16 print("Last item was:", result)
>>>Output
List was empty
Understanding how loop variables behave in Python helps avoid common bugs, especially when accessing them after the loop ends:
Variables persist after loops
Variables persist after loops
The loop variable keeps its last assigned value after the loop completes
Use descriptive names
Use descriptive names
Prefer item, row, or char over single letters like i or x
Empty loops skip assignment
Empty loops skip assignment
If the sequence is empty, the loop variable is never created
Initialize before the loop
Initialize before the loop
Set a default value before the loop if you need the variable afterward

Nested Loop Scope

Each loop has its own variable, but inner loops can access outer loop variables:
1# Multiplication table
2for i in range(1, 4):
3 for j in range(1, 4):
4 product = i * j
5 print(str(i) + " x " + str(j) + " = " + str(product))
6 print("---")
7
8# Access both variables after loops
9print("Final i:", i)
10print("Final j:", j)
>>>Output
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---
Final i: 3
Final j: 3

Common Mistakes

These are frequent errors when writing loops:
1# MISTAKE 1: Modifying list while iterating
2# DON'T DO THIS:
3# items = [1, 2, 3, 4, 5]
4# for item in items:
5# if item % 2 == 0:
6# items.remove(item) # Dangerous!
7
8# CORRECT: Create new list or iterate over copy
9items = [1, 2, 3, 4, 5]
10odds = [item for item in items if item % 2 != 0]
11print("Odds:", odds)
12
13# MISTAKE 2: Off-by-one with range
14# Want 1-5? Use range(1, 6)
15for i in range(1, 6):
16 pass
17print("Last i:", i)
18
19# MISTAKE 3: Forgetting to increment in while
20count = 0
21while count < 3:
22 print(count)
23 count += 1
>>>Output
Odds: [1, 3, 5]
Last i: 5
0
1
2
Loops are essential for automating repetitive tasks and processing collections of data. Put these fundamentals to the test with hands-on challenges in the Python Builder.
PUTTING IT ALL TOGETHER

> You are a data analyst at The Washington Post writing a Python script to iterate through a batch of 50 daily report files, extract the key engagement metric from each, and print a summary line for every file processed.

for loop iterates through each file in the batch list so no file is skipped or manually tracked.
range() generates the sequence of indices needed to access report files in a specific processing order.
while loop continues processing until a stop condition like reaching the end of records or hitting a file error is met.
The loop body executes the same metric extraction logic for every file without duplicating code across the script.
KEY TAKEAWAYS
for loops iterate over each item in a sequence (list, string, tuple)
range(n) generates 0 to n-1; range(start, stop, step) for full control
while loops repeat while condition is True; ensure the condition eventually becomes False
break exits the loop immediately; continue skips to the next iteration
Loop variables persist after the loop ends with their last value
Use for loops when you know how many iterations; while loops when you do not
Never modify a list while iterating over it directly
Remember that range(stop) does not include the stop value

Repeating actions efficiently

Category
Python
Difficulty
beginner
Duration
39 minutes
Challenges
0 hands-on challenges

Topics covered: Iterating with for Loops, range() Function, Loops with while, Using break and continue, Loop Variable Scope

Lesson Sections

  1. Iterating with for Loops (concepts: pyForBasic)

    A for loop repeats a block of code once for each item in a sequence. Without one, processing fifty files means writing fifty nearly-identical blocks of code. A loop collapses all of that into three lines. Basic for Loop Syntax Looping Over Strings Strings are sequences of characters, so you can loop over them character by character: Each character in the string becomes the loop variable in turn. This is useful for analyzing text character by character. Accumulating Results A common pattern is to

  2. range() Function

    range() with One Argument range() with Two Arguments range() with Three Args range() for Index Access Sequences from range() Repeating Actions N Times Sometimes you just need to repeat an action a specific number of times without caring about the loop variable. By convention, you can use an underscore for variables you do not intend to use:

  3. Loops with while (concepts: pyWhileLoops)

    Basic while Syntax The loop checks the condition, executes the body if True, then checks again. When count reaches 5, the condition becomes False and the loop ends. Here is the execution model step by step: Comparing while and for Choose the right loop type based on your situation: When deciding which loop type to use, keep these practical rules in mind. They cover the most common scenarios you will encounter in real code. Common while Patterns Here are typical use cases for while loops: Avoidin

  4. Using break and continue (concepts: pyBreakContinue)

    The break Statement The continue Statement break vs continue Understanding the difference is crucial: break and continue in while These statements work the same way in while loops: Combining break with Flags Sometimes you need to know whether a loop exited normally or via break. A flag variable can track this distinction: The flag variable starts False and becomes True only if the target is found. After the loop, you check the flag to determine the outcome. This pattern is useful when you need d

  5. Loop Variable Scope

    Loop Variables Persist Empty Loops: Undefined Vars If a loop never executes (empty sequence), the loop variable is never assigned: Understanding how loop variables behave in Python helps avoid common bugs, especially when accessing them after the loop ends: Nested Loop Scope Each loop has its own variable, but inner loops can access outer loop variables: Common Mistakes These are frequent errors when writing loops: Loops are essential for automating repetitive tasks and processing collections of