We use loops when we want to keep repeating a set of statements.
If we know exactly how many times we'll be repeating it, we could just copy/paste the code that many times. We could even put the code into a function and just call that function that many times. However, this is not good practice, and it's impractical—what if you have to call the function 100 times? 1000? etc.
That's why there is the concept of looping. There are two ways to loop that we've taught you: while and for loops (although there was no need to use for in either of the lab problems yesterday).
while [expression that evaluates True or False]:
[statements to be executed]
for [variable] in range([start], stop, [step]):
[statements to be executed]
While Loop:
The computer first evaluates the expression.
If it's true, it executes the statements.
Then it returns to the expression and evaluates it again.
If it's true again, it executes the statements again.
This keeps going, repeating as long as the expression is true.
Example: If you think in terms of "until," e.g., "play the game until there are no stones," we can always write that in terms of "while" by just negating the expression, e.g., "play the game WHILE there ARE stones."
For Loop and Range Statements:
The for and range statements can initially be confusing.
Play around with range in the shell to understand what start, stop, and step mean.
Example: range(1, 11, 2) returns the numbers 1, 3, 5, 7, 9.
Remember: The stop number is never included.
Key Insight:
Once you understand range, then for just means that through each iteration of the loop ("iteration" means a time that you're executing the statements inside), the variable after for is assigned the next number in that range.
Practice:
Keep playing around with these; it'll start to make sense!
---
To mark this module as complete, you must finish this quiz. Once submitted, you'll need to wait 2 hours before attempting it again.