Back to Sessions
Session 5
1 lesson completed
While Loops
CompletedAssignment
Complete regenerate using a while loop. While current_health < max_health AND enemy_distance > 3: add 1 to health and subtract 2 from enemy_distance. Return the new current_health. Place return outside the loop.
Solution
def regenerate(current_health, max_health, enemy_distance):
while current_health < max_health and enemy_distance > 3:
current_health += 1
enemy_distance -= 2
return current_healthConcept
while loops, combining conditions with and, mutating variables inside loops with += and -=, placing return outside the loop
How it went
First attempt had the right instinct but used a second while loop instead of combining both conditions, and wrote enemy_distance - 2 instead of enemy_distance -= 2. Once shown a parallel fuel tank example, mapped concepts across correctly. 8/8 tests passing.
Ratings
Concept grasp: Solid
First attempt: Partial — right idea, wrong syntax
Pattern transfer: Good — applied example to own problem cleanly
Final solution: Clean and correct
Key takeaways
- →Calculating vs assigning: `x - 2` calculates and throws away. Use `x -= 2` to actually change the variable
- →return goes outside the loop — inside = returns after first iteration, outside = runs once loop finishes