Lesson 9: While Loop
While Loop is another powerful repetition structure in Python.
Its main difference from For Loop is that:
- For Loop iterates for a fixed amount of time
- While Loop iterates as long as its statement is True (It can run indefinitely if the statement doesn’t change)
Let’s start with some examples:
i=1 while i==1: print("Hello World!")
Above code will run indefinitely and this would cause a nuisance and potentially a minor crash in your compiler.
What happens is compiler checks if 1=1 (this is shown with double equal sign in Python statements: == ) which is True so it runs the line print(“Hello World!”).
Then it goes back and checks if 1==1 again and prints again and so on.
That’s why you will see that value inside While Loop’s statement usually changes and so it can stop when a certain condition is triggered.
This will be more clear with a few more examples and give you some ideas.
Function : N/A
No new function will be introduced in this lesson.
While Loops are particularly useful when you don’t know how many iterations will be suitable.
Here are some examples:
- While (mouse_is_moving):
- While (lights_are_on):
- While (team_is_winning):
- While (user_age < 18):
These are only some vague ideas about the type of situations while loops can be preferred rather than for loops.
1) First line starts with while followed by a statement
2) There is a colon(:) at the end of first line
2) After first line following lines should be indented
1) Don’t forget the colon (:) at the end of the first line just like for loops
2) Don’t forget the indent after the first line also just like for loops
i = 0
while i < 3:
i = i+1
In this case, while loop will iterate 3 times, while it’s 0, 1 and 2. Once it’s incremented to 3 it will not satisfy the logical statement (i<3) and exit the loop.
1- When you forget to include the operation (such as i = i+1) that causes the loop to exit, your code will loop forever.
If this happens just interrupt your compiler so that your code is stopped externally. Most programming software and terminals have either shortcuts (sometimes ctrl+c, ctrl+q or ctrl+z) or visual buttons to stop the code from running.
How about using while loop to iterate through a list? This is possible with the help of len function but, it’s just so much more convenient to use a for loop for such tasks. Let’s see:
lst = [3, 5, 9, 11]
while i < len(lst):
i = i+1
Advanced Concepts (Optional)
Nested For Loop
1- In some situations you might need a nested loop structure. We have previously seen that lists can be consisted of many type of different data including other lists. Let’s see an example of nested list and nested while loop.
i = 0
j = 0
j = j+1
i = i+1
As you can see outer loop runs 3 times (while i is 0,1 and 2) And the inner loop runs twice each time (while j is 0 and 1)
Break & Continue
Under Guiding Lights by Fracchetti Lorenzo