πΎWhat is a Loop?
While and For, among other things.
Say, we want to print "Hello!" 3 times. One might consider doing it like this:
What if you wanted to print the same thing, say, a hundred times? It is clearly impractical to write this statement a hundred times. Instead, we'll use loops to execute this block of code.
This can be done through various different syntaxes. First, we introduce the for loop:
Next, we show how you can write the same piece of code using a while loop:
The Anatomy of a Loop
A loop has four parts:
Initialization: Setting up the initial, starting value for the variable that our loop uses.
Condition: The condition statement, which stops the looping when it becomes false.
Execution Suite: The code inside the loop that gets executed every time the loop runs.
Updation: Updating the looping variable to get us closer to making the condition false.
We use the while loop to mark out these four sections.
A for loop is similar, but with lots of this stuff hidden away behind the scenes. We iterate over the range, such that range is defined as range(start=0, stop, step=1)
where our values start at start
(inclusive), end at stop
(exclusive) and proceed by step
. As an example, range(1, 5, 2)
would return the values 1 and 3. The default values for start and step are 0 and 1 respectively. Thus, something like
Prints out all the numbers from 1 to 9.
Difference between a for and a while loop
So when do we use a for loop and when do we use a while loop? There isn't any hard and fast rule, but the general rule of thumb is this: if we have a fixed number of times we want to loop over a piece of code, use a for loop. If the number of times we loop over something depends over a condition without a fixed number, use a while loop.
We'll attempt enough examples with both to get intuition about when to use which one!
Last updated