Loops
Loops: Automating Repetition¶
Loops are used when you want to execute a block of code multiple times without writing it over and over.
1. The "While" Loop¶
The loop continues as long as a condition is True. - Logic: "Keep washing the dishes while there are still dirty plates." - Danger: If the condition never becomes False, you get an Infinite Loop.
2. The "For" Loop¶
The loop runs for a fixed number of times or for every item in a collection. - Logic: "For every student in the class, give them a textbook."
Loop Control: Break & Continue¶
- Break: Immediately stop the loop and exit.
- Continue: Skip the rest of the current turn and jump to the next one.
Why use Loops?
Loops are the reason computers are powerful. They never get tired of doing the same thing 1,000,000 times!