🔁 Repeating Actions Conditionally
Sometimes, you need the computer to do something over and over, but only while a certain situation is true.
Imagine checking your phone for a message repeatedly, until you finally receive it.
Python's while
loop is perfect for this conditional repetition.
⚙️ The `while` Loop Structure
It checks a condition, then runs the indented code if it's true.
The whileThe keyword that starts the conditional loop. statement is followed by a conditionAn expression that evaluates to True or False (e.g., count < 3). and a colon :
.
The code to be repeated must be indentedUsually 4 spaces. This tells Python what's inside the loop. underneath the `while` line.
The loop continues as long as the condition is TrueThe loop keeps running.. It stops when the condition becomes FalseThe loop terminates, and Python moves to the next line after the loop..
It's crucial that something inside the loop eventually makes the condition False! (Like count = count + 1
).
🚦 The Condition is Key
The loop's fate depends entirely on the condition.
Before each potential repetition (iteration), Python re-evaluates the `while` condition.
If True
: Run the indented code block again.
If False
: Skip the block and continue after the loop.
Watch out! If the condition never becomes False
, you create an infinite loop (your program gets stuck!).
🧠 Quick Check!
Module 14 Theory Complete!
Excellent! You've learned how the `while` loop repeats actions based on a condition.
Time to practice this powerful looping structure in the Practice Zone or tackle the Advanced Practice.