Python 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!
1. The while Loop¶
With the while loop we can execute a set of statements as long as a condition is true.
2. The for Loop¶
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
The range() Function¶
To loop through a set of code a specified number of times, we can use the range() function.
Else in Loop¶
The else keyword in a for or while loop specifies a block of code to be executed when the loop is finished: