1.12 While Loops
 
While Loops in Karel | CS Lesson
01 / 14
๐Ÿค–
โ— CodeHS Unit 1  ยท  Lesson 1.12

While
Loops
in Karel

Teaching Karel to repeat actions until a condition becomes false โ€” building general solutions that work across any world.

Duration
60 Minutes
Level
Introductory CS
Platform
CodeHS.com

Question of the Day

๐ŸŽ‚

"You're baking a cake and the recipe says:
Mix until smooth.
How many times do you mix?"

You don't know in advance โ€” you keep mixing until the condition is met.

FOR LOOP THINKING

"Mix exactly 10 times" โ†’ Fixed repetitions, known in advance

WHILE LOOP THINKING

"Mix until smooth" โ†’ Unknown repetitions, condition-based

Today's Goal

Students will construct while loops in Python-Karel to solve open-ended world problems by evaluating conditions and designing general solutions that function correctly across multiple configurations.

Bloom's: Create Problem Solving Abstraction General Solutions

Students will be able to:

  • Explain the difference between for loops and while loops
  • Write while loop syntax using a condition and indented body
  • Apply while loops to solve problems on multiple Karel worlds
  • Predict and prevent infinite loops by analyzing conditions

Lesson Checklist

๐Ÿ“‹ Practice

Watch 1.12.1 Video Lesson VIDEO
Concept comparison (for vs while) DISCUSS
Trace code examples together MODEL
Flow diagram walkthrough VISUAL

๐Ÿ’ป Process + Product

1.12.2 Quiz ASSESS
1.12.3 Move to Wall CODE
1.12.4 Follow Yellow Ball Road CODE
1.12.5 Lay Row of Tennis Balls CODE
1.12.6 Big Tower CHALLENGE
Exit Ticket Closure REFLECT
LESSON TIME
60 min
Intro ยท Concept ยท Coding ยท Closure

For Loop vs While Loop

Aspect ๐Ÿ”„ For Loop โญ• While Loop
Repetitions Fixed, known in advance Unknown โ€” depends on world state
Control A number (e.g., for i in range(4)) A condition (e.g., front_is_clear())
Use when... You know exactly how many times to repeat You must check the world each iteration
Risk Off-by-one errors Infinite loop if condition never becomes False
Karel Example for i in range(5): move() while front_is_clear(): move()
For Loop Analogy

Run 3 laps โ€” you know the count before you start.

While Loop Analogy

Run until you reach the finish line โ€” you don't know the distance.

While Loop Syntax

PYTHON while condition:
    # code to execute
    # while condition is True
EXAMPLE 1 while front_is_clear():
    move()
EXAMPLE 2 while not facing_north():
    turn_left()

Anatomy Breakdown

  • while โ€” the keyword that starts the loop
  • condition โ€” a True/False expression checked before each run
  • : โ€” the colon is required, just like in functions
  • Indentation โ€” the loop body must be indented 4 spaces
  • not โ€” can flip a condition (e.g., not facing_north)
โš  Infinite Loop Warning

If the condition never becomes False, the loop runs forever! Always ask: "Will this condition eventually be False?"

How It Works โ€” Flowchart

START
Check condition
(e.g., front_is_clear())
TRUE โ–ผ
Execute body
e.g., move()
โ†บ loop back
FALSE โ–ผ
EXIT loop
continue program

Three key moments:

  • Before the loop starts โ€” condition is checked. If already False, body never runs!
  • Each iteration โ€” condition is re-checked before the body executes again
  • When condition = False โ€” loop exits and the program continues
# Karel moves until hitting a wall
while front_is_clear():
    move()
# now Karel is AT the wall

All Four Concepts at a Glance

๐Ÿ”ง
FUNCTION

A named block of reusable code. Defines a new command Karel can use.

def turn_right():
  for i in range(3):
    turn_left()
Reusability
๐Ÿ”„
FOR LOOP

Repeats code a fixed, known number of times. Controlled by a counter.

for i in range(4):
  move()
Fixed Count
โญ•
WHILE LOOP

Repeats while a condition is true. Works for unknown repetition counts.

while front_is_clear():
  move()
Condition-Based
โ“
IF / ELSE

Runs code only if a condition is true. Optionally runs different code otherwise.

if front_is_clear():
  move()
else:
  turn_left()
Decision Making

Classic While Loop Programs

๐Ÿšง

Move to Wall

Karel moves forward until it hits a wall โ€” works on any world size!

while front_is_clear():
  move()
Exercise 1.12.3
๐Ÿงญ

Face North

Karel turns left until it faces north โ€” no matter its starting direction.

while not facing_north():
  turn_left()
Direction Control
๐ŸŽพ

Lay Row of Balls

Karel places beepers until reaching a wall โ€” row length adapts!

while front_is_clear():
  put_ball()
  move()
put_ball() # fencepost!
Exercise 1.12.5
๐Ÿšง
FENCEPOST BUG

Some problems require one extra action after the loop ends. Always ask: does the last position need an action too?

CodeHS Exercises

1.12.1
While Loops in Karel โ€” Video Introduction
VIDEO
1.12.2
While Loops in Karel โ€” Check for Understanding
QUIZ
1.12.3
Move to Wall โ€” Karel moves until hitting an obstacle
CODE
1.12.4
Follow The Yellow Ball Road โ€” navigate while beepers remain
CODE
1.12.5
Lay Row of Tennis Balls โ€” place beepers until wall (fencepost)
CODE
1.12.6
๐Ÿ† Big Tower โ€” face north + build upward while loop challenge
CHALLENGE
๐Ÿ’ก TESTING TIP

Test your loop body and condition independently before combining them. Run on at least 2 different world sizes!

Teaching Considerations

  • Emphasize the difference: For loops = fixed count. While loops = unknown count based on world state. Repeat this distinction often.
  • Infinite loops: Show a live infinite loop (then stop it). Make the danger real and memorable before students encounter it.
  • Fencepost errors: Use the fence analogy โ€” 3 sections need 4 posts. Some problems need one extra action outside the loop.
  • General solutions: Always test on multiple world sizes. A program that only works on one world is not a real while loop solution.
  • Iterative testing: Build the condition first, test it. Then add the body, test again. Don't write the whole loop at once.
  • Vocabulary: Continuously reinforce: condition, iteration, body, infinite loop, general solution.
while loop
A loop that repeats while a condition remains True
condition
A True/False expression checked before each iteration
general solution
A program that works on many world configurations, not just one
infinite loop
A loop whose condition never becomes False โ€” runs forever
fencepost bug
When an action must occur one more time than the loop runs
iteration
One complete execution of the loop body

Hands-On Exit Ticket

ON PAPER OR WHITEBOARD:

1
Trace the Code โ€” Given a 5-wide world, how many times does this loop run?
while front_is_clear():
  move()
2
Fix the Bug โ€” This loop causes an infinite loop. Why?
while not facing_north():
  move()
3
Write Your Own โ€” Write a while loop to pick up all beepers on a row (use balls_present()).

REFLECTION PROMPTS:

  • When would you choose a while loop over a for loop? Give an example.
  • What question should you always ask before writing a while loop? (Will the condition eventually be False?)
  • In your own words: what makes a solution "general"?
EXIT TICKET

On a sticky note (or Google Form): Write the ONE thing you now understand about while loops that you didn't before today.

Kahoot! Unit 1 Review

Last 30 minutes of the 90-min class. Covers Units 1.1 โ€“ 1.12. Sample questions on next slide โ–ธ

UNITS COVERED
1.1 Intro to Karel 1.2 More Basic Karel 1.3 Can't Turn Right 1.4 Functions 1.5 Top-Down Design 1.6 Commenting 1.7 Abstraction 1.9 For Loops 1.10 If Statements 1.11 If/Else 1.12 While Loops
GAME FORMAT
  • ~22 questions โ€” approximately 2 per unit
  • Multiple choice โ€” 4 options, 20 seconds each
  • Mix of: syntax, concept, code-reading, debugging
  • Encourage discussion after tricky questions
Unit 1 Review ยท Sample Questions
20
QUESTION 1 / 6
What does this code do?
while front_is_clear():  move()
โ–ฒ
Moves Karel exactly 5 times
โ—†
Moves Karel until it hits a wall
โ—
Turns Karel left forever
โ– 
Picks up all beepers
โœ“ Correct: B โ€” Moves Karel until it hits a wall (front_is_clear() becomes False)
Last updated  2026/03/24 16:02:40 PDTHits  88