Python · Loops
While Loops
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Introduction to While Loops
A while loop allows you to repeat a block of code as long as a condition is True. Unlike for loops which iterate over a sequence, while loops continue until a condition becomes False.
The basic syntax is:
while condition: # code to execute # update something to eventually make the condition False
Here's a simple example of a while loop that counts from 1 to 5:
count = 1 # Initialize counter # Loop while count is less than or equal to 5 while count <= 5: print(count) count = count + 1 # Update the counter print("Loop finished!")
Notice three important parts: 1. We initialize a variable before the loop 2. We use this variable in the condition 3. We update the variable inside the loop. This way, when the condition becomes False, the loop stops.
Exercise 2 — How While Loops Work
Let's understand how a while loop works step by step:
1. Python evaluates the condition 2. If the condition is True, the code inside the loop executes 3. After executing the code, Python goes back to step 1 4. If the condition is False, Python skips the loop and continues with the code after it
Let's trace through this example with codemon_level starting at 1 and increasing until it reaches 5:
codemon_level = 1 while codemon_level < 5: print("Training Codémon! Current level:", codemon_level) codemon_level = codemon_level + 1 print("Training complete! Final level:", codemon_level)
Loop Execution Trace
1. Start: codemon_level = 1 2. Check: 1 < 5? Yes → Execute loop 3. Print level 1, increase to 2 4. Check: 2 < 5? Yes → Execute loop 5. Print level 2, increase to 3 6. Check: 3 < 5? Yes → Execute loop 7. Print level 3, increase to 4 8. Check: 4 < 5? Yes → Execute loop 9. Print level 4, increase to 5 10. Check: 5 < 5? No → Exit loop 11. Print final level: 5
Exercise 3 — Correct While Loop Syntax
Which of the following is the correct syntax for a while loop in Python?
Options
• ```while condition:```
• ```while (condition) {}```
• ```while condition```
• ```while: condition```
Hint : Remember : a while loop in Python is built with the keyword 'while', followed by a condition, a colon, and then the indented block of code that will execute as long as the condition is true.
Exercise 4 — Complete the While Loop
Complete the while loop to print numbers from 1 to 5:
num = 1 ____ num <= 5: print(num) num = num ____ 1
Options: while for print input + - *
Hint : A while loop needs the 'while' keyword, followed by a condition that will become False eventually.
Exercise 5 — Danger: Infinite Loops
A common error with while loops is creating an infinite loop - a loop that never ends because its condition never becomes False.
This happens when you forget to update the variable(s) used in the condition, or update them incorrectly.
IMPORTANT: Avoid Infinite Loops
If you run an infinite loop, your program might freeze or crash. Make sure your loop condition can eventually become False. We won't run the code examples for infinite loops below to avoid crashing your app!
Example of an infinite loop (DO NOT RUN THIS!):
# This would run forever! counter = 1 while counter <= 5: print(counter) # Oops! We forgot to increment counter! # counter stays 1 forever, we never leave the loop cause we stay under 5!
Here's the correct version:
counter = 1 while counter <= 5: print(counter) counter = counter + 1 # Don't forget this line!
Exercise 6 — Spot the Infinite Loop
Which of the following code snippets would create an infinite loop?
Options
• power = 5 while power < 10: print("Power level:", power) power = power - 1
• health = 100 while health > 0: print("Codémon is healthy!") health = health - 10
• level = 1 while level < 10: print("Current level:", level) level = level + 1
• x = 0 while x < 5: print(x) x = x + 1
Hint : Look at how the variable in the condition changes within the loop body. Will it ever make the condition false?
Exercise 7 — Match While Loops with Outputs
Match each while loop with its correct output:
Items to match
• x = 1 while x <= 3: print(x) x += 1
• x = 5 while x > 0: print(x) x -= 2
• x = 0 while x < 3: x += 1 print(x * 2)
• x = 10 while x > 5: print(x) x -= 1
Definitions
• 1 2 3
• 5 3 1
• 2 4 6
• 10 9 8 7 6
Exercise 8 — Fix the Infinite Loop
This code would create an infinite loop. Add a line to fix it so that it counts from 1 to 5 and then stops:
count = 1 while count <= 5: print("Count is:", count) ____ = ____ ____ ____
Options: count count 1 total increment 0 +
Hint : To avoid an infinite loop, you need to update the variable used in the condition so it eventually becomes False.
Exercise 9 — Predicting While Loop Output
What will be the output of this code?
health = 20 damage = 6 while health > 0: print("Health:", health) health = health - damage
Options
• Health: 20 Health: 14 Health: 8 Health: 2
• Health: 20 Health: 14 Health: 8
• Health: 20 Health: 14 Health: 8 Health: 2 Health: -4
• Health: 14 Health: 8 Health: 2
Hint : Trace through the loop step by step. The condition is checked before each iteration, so it stops when health ≤ 0.
Exercise 10 — Understanding When While Loops Run
When does the code inside a while loop execute?
Options
• Only when the condition evaluates to True
• Only when the condition evaluates to False
• At least once, regardless of the condition
• Always exactly once
Hint : Remember that a while loop checks its condition first, then only executes if the condition is True.
Exercise 11 — Codémon Challenge - Battle Simulator
Welcome to the Battle Simulator! You need to simulate a Codémon battle using a while loop. Simulate a battle where a Codémon has 50 health points and takes 7 damage each turn. Use a while loop to display the health after each attack until health reaches 0 or below.
Starter code
print("=== BATTLE SIMULATOR ===") health = 50 damage = 7 turn = 1 # Simulate battle with health reduction
Back to the course