While Loops
While loops are another way to run a section of code multiple times.
A while
loop is similar to a for
loop, but it runs indefinitely until a condition is ``.
A while
loop looks like this:
while condition:
# do something
Borrowing from the previous example, let's say we want to print the numbers from 1 to 10.
Here's how it's done using a while loop:
i = 1
while i <= 10:
print(i)
i = i + 1
Let's break down how this works:
First, let's define a variable i
to keep track of the current number.
i = 1
Then, we want to check if i
is less than or equal to 10.
while i <= 10:
If the current value of i
is less than 10, then we want to print the current value of i
.
print(i)
Then, we want to increment i
by 1. This is very important, otherwise the loop will never end (it will run forever).
i = i + 1
This is how the loop works:
- Every time the loop finishes running, it goes back to the beginning and checks if the condition is
true
- It checks if the condition is
true
by substituting the current value ofi
in its place
Infinite loops
Note the last line of the above example. This is one of the dangers of using while
loops.
What if we didn't increment i
by 1?
Let's say we did this:
i = 1
while i <= 10:
print(i)
Since i
will always be equal to 1, then the condition i <= 10
will always equal 1 <= 10
, be equal to true
, and the loop will never end.
THIS WILL CRASH YOUR COMPUTER!!!
Always make sure that your while
loop has a condition that is false
at some point. Otherwise, the loop will run forever (called an infinite loop).
You can usually avoid infinite loops by increasing/decreasing the variable in the condition by 1
.
You can do this by using i = i + 1
or i = i - 1
.
The shorthand way of doing this is i += 1
or i -= 1
.