While Loops
Introduction
Welcome to the chapter on while loops! Here youβll learn how to use them to help the knight collect coins more efficiently, understand new surrounding-checking methods, and compare strings in Python.
Understanding While Loops
A while loop runs as long as its condition is True. This is useful when you need repeated actions but donβt know the exact number of iterations in advance.
1234i = 0 while i < 5: print("Incrementing:", i) i += 1
Knight's Surroundings
The knight can inspect nearby cells using:
object_up(), object_down(), object_left(), object_right().
Each returns "wall", "coin", or "empty".
String Comparisons
Use == and != to compare strings and decide actions based on what the knight detects.
Example
Hereβs an example showing how a while loop helps the knight collect all coins in a column.
knight.py
In this example, the collect_column function uses a while loop to collect all the coins in a column. The knight checks if there is coin above it and continues to pick and move up until there is no more coins. After collecting, the knight moves back down to its original position.
Swipe to start coding
Solution
Thanks for your feedback!
knight.py
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain how the while loop works in the code sample?
What do the `object_up()`, `object_down()`, etc. functions do?
How does string comparison help the knight decide what to do?
Awesome!
Completion rate improved to 2.94
While Loops
Swipe to show menu
Introduction
Welcome to the chapter on while loops! Here youβll learn how to use them to help the knight collect coins more efficiently, understand new surrounding-checking methods, and compare strings in Python.
Understanding While Loops
A while loop runs as long as its condition is True. This is useful when you need repeated actions but donβt know the exact number of iterations in advance.
1234i = 0 while i < 5: print("Incrementing:", i) i += 1
Knight's Surroundings
The knight can inspect nearby cells using:
object_up(), object_down(), object_left(), object_right().
Each returns "wall", "coin", or "empty".
String Comparisons
Use == and != to compare strings and decide actions based on what the knight detects.
Example
Hereβs an example showing how a while loop helps the knight collect all coins in a column.
knight.py
In this example, the collect_column function uses a while loop to collect all the coins in a column. The knight checks if there is coin above it and continues to pick and move up until there is no more coins. After collecting, the knight moves back down to its original position.
Swipe to start coding
Solution
Thanks for your feedback!
knight.py