Iteration Lesson – Big Idea 3.8

Warm-Up

Think about these questions:

  • How do you brush your teeth every morning?
  • Do you repeat steps until your teeth feel clean?
  • What are other examples in daily life where we repeat steps?

Iteration is like repeating those steps in code until a condition is met.

Key Vocabulary

  • Loop – A structure that repeats instructions.
  • For loop – Repeats a block of code a specific number of times.
  • While loop – Repeats a block of code as long as a condition is true.
  • Iteration – Each repetition of the loop body.

Language comparison: Python vs JavaScript

Short notes for beginners:

  • Python uses indentation to mark the loop body; JavaScript uses braces {}.
  • Python commonly uses range() and direct iteration over lists; JavaScript often uses for, for...of, or array methods like .forEach().
  • Behavior of break and continue is the same in both languages but the syntax differs slightly.
  • When converting between languages, focus on the loop’s goal (counting, iterating, waiting for a condition) and pick the matching pattern in the target language.

For loops

A for loop is used when you know (or can determine) how many times you want to repeat something. In Python, for variable in sequence: runs the body once for each item in the sequence.

for loops are definate loops meaning they only run for a definate amount of variables

Key parts:

  • variable: a name that refers to the current item or index each iteration.
  • sequence: something you can loop over (like range(), lists, strings).

What happens during a for loop (step-by-step)

Let’s look at a tiny loop and trace exactly what the computer does each step. This helps us see how the loop variable changes and when the loop stops.

Code to trace:

for i in range(1, 4):
    print('i is', i)

Step-by-step explanation:

  1. range(1, 4) creates the sequence [1, 2, 3].
  2. The loop picks the first item (1) and assigns it to i.
  3. The body print('i is', i) runs and shows i is 1.
  4. The loop picks the next item (2), assigns to i, runs the body, prints i is 2.
  5. The loop picks the next item (3), prints i is 3.
  6. There are no more items, so the loop ends.

Try changing the range numbers to see more or fewer iterations.

# Run the tiny loop so you can see the trace
for i in range(1, 4):
    print('current value of i =', i)

for Popcorn Hack: Iterate a list of names

Example: iterate a list of names and greet each person.

blanks = ['', '', '']
for blank in blanks:
    print('Hello,', blank)

Python vs JavaScript: for Loops

1) Simple for loop (counting)

Python explanation: for i in range(start, end) runs i through a sequence of numbers.

for i in range(1, 6):
    print(i)  # prints 1,2,3,4,5

JavaScript explanation: for (let i = start; i < end; i++) is the usual counting loop.

for (let i = 1; i <= 5; i++) {
  console.log(i); // prints 1,2,3,4,5
}

2) Looping over an array/list

Python (list): use for item in list:

names = ['Anwita','Nicholas','Varada']
for name in names:
    print('Hello', name)

JavaScript (array): use for...of or index loop

const names = ['Anwita','Nicholas','Varada'];
for (const name of names) {
  console.log('Hello', name);
}

while Loop

A while loop repeats as long as a condition remains true. Use while when you don’t know in advance how many iterations you need — just the condition that should stop the loop.

A while loop is an indefinate loop meaning it will repeat as long as a condition is true Important ideas:

  • Ensure something in the loop eventually makes the condition false (like updating a counter).
  • Be careful with input-driven loops — always validate and provide a clear exit path.

Example: Create a list of numbers and end and 5

We are going to use what we learned previously in math expressions!

# Initialize a variable
num = 1

# While loop starts
while num <= 5: # This loop will continue as long as num is less than or equal to 5
    print(num) # Print the current value of the number
    num += 1  # This is equivalent to num = num + 1
# End of the loop

Homework help!

To do what we did above with the list of names, you can also use a while loop!

names = ['Anwita', 'Nicholas', 'Varada']

# i = 0 # Initialize a variable i to 0
# while i < ___(names): # Loop continues as long as i is less than the length of the names list (The length is 3)
#    print('Hello', names[i]) # Print the name at index i
#   i += 1

Doubling using while loops

This loop will continue as long as the number is less than or equal to 100 starting at 2

# Keep doubling until the number is greater than 100
num = 2 # Start with 2
while num <= 100: # This loop will continue as long as num is less than or equal to 100
    print(num) # Print the current value of the number
    num = num * 2 # This is equivalent to num *= 2

JavaScript equivalent

Here is the same behavior in JavaScript (prints to console):

// Start with 2, keep doubling while <= 100
let num = 2;
while (num <= 100) {
  console.log(num);
  num = num * 2; // or num *= 2 for shorter syntax
}

while Popcorn Hack: countdown with a safety counter

This while loop counts down from 10 to 1. Let’s built a countdown to blast off with while loops!

n = 10
# while n > 0:  
#    print('T minus', n)
#    n -= 1 # same as n = n - 1

#print('Blast off!') 

JavaScript vs. Python: while Loops

3) while loop (indefinite)

Python: repeat until condition false

count = 1
while count <= 5:
    print(count)
    count += 1

JavaScript: similar structure, but different syntax

let count = 1;
while (count <= 5) {
  console.log(count);
  count += 1;
}

while loop in arrays/lists

names = ['Anwita', 'Nicholas', 'Varada']
i = 0
while i < len(names):
    print('Hello', names[i])
    i += 1

let names = ['Anwita', 'Nicholas', 'Varada'];
let i = 0;
while (i < names.length) {
    console.log('Hello ' + names[i]);
    i++;
}

Control flow inside loops: break and continue

  • break exits the entire loop immediately.
  • continue skips the rest of the current iteration and goes to the next one.

Example: print numbers 1–6 but skip 3 and stop when you reach 5.

for n in range(1, 8): # numbers 1 to 8
    if n == 3: # when n is 3
        continue  # skip number 3
    if n == 6: # when n is 6
        break  # stop the whole loop at 6
    print(n) # what number is printed

# Output: 1
#         2
#         4
#         5

4) break and continue

Python:

for i in range(1, 6):
    if i == 3:
        continue  # skip the rest of this iteration
    if i == 5:
        break     # exit the loop early
    print(i) 

JavaScript:

for (let i = 1; i <= 5; i++) {
  if (i === 3) continue;
  if (i === 5) break;
  console.log(i);
}

Iterations Game — Multiple Choice (JavaScript / Python)

Choose a language, read the snippet, and pick the correct output or behavior. You will get immediate “Correct” or “Incorrect” feedback and an explanation.

Question 1


    

Check for Understanding

Question: What will this code output?

for i in range(3):
    print("hi")
  • A) hi
  • B) hi hi
  • C) hi hi hi
  • D) Nothing

Correct Answer: C