← Back to Loops
πŸ’š

Health Regen

5 of 6

Exercise 4: Health Regen

Your character has taken damage and is regenerating health. Each turn they recover 5 HP, but health can't go above the max HP of 100.

Write a while loop that heals the character until they're at full health, and track how many turns it takes.

Example (starting at 72 HP):

Turn 1: 72 β†’ 77 HP
Turn 2: 77 β†’ 82 HP
Turn 3: 82 β†’ 87 HP
Turn 4: 87 β†’ 92 HP
Turn 5: 92 β†’ 97 HP
Turn 6: 97 β†’ 100 HP
Fully healed in 6 turns!

Notice turn 6: 97 + 5 = 102, but it caps at 100.


Starter Code

health = 72 max_health = 100 regen = 5 turns = 0 while health < ___: old_health = health health += regen # Make sure health doesn't go above max if health > max_health: health = ___ turns += 1 print(f"Turn {turns}: {old_health} β†’ {health} HP") print(f"Fully healed in {turns} turns!")

Hints

Hint 1 β€” The while condition

Keep healing while health is below max: while health < max_health:

Hint 2 β€” Capping the health

After adding regen, check if health went over max. If so, set it to max:

if health > max_health: health = max_health
Hint 3 β€” Tracking old health

Save the current health before adding regen so you can show the "before β†’ after" in the print statement.

πŸ’»

Try it yourself

Code: Health Regen

Loading Python runtime…
Python …
Loading...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect

βœ… Functions, classes, recursion, print()

❌ No file system, subprocess, OS access, or network requests

❌ No pip install (all supported modules are pre-loaded)

⏱️ 5 second execution time limit