Welcome to the next part of our Python Tutorial! Today we will cover the while-Loop.
The while-Loop is different from the for-Loop because it relies on a certain condition we can define.
Let's look at a little example:
i = 0
while i <= 10:
print(i)
i = i + 1
This example basically does the same thing as the one we used for the for-Loop. It counts from 0 to 10.
But this time we didn't have to use a list from which python takes the element, we defined our own element which is checked in every run.
To tell the loop what to check, we use operators. The most important operators are those:
==
a is the same as b
<=
a is smaller or equal as b
>=
a is larger or equal as b
<
a is smaller than b
>
a is larger than b
!=
a is not the same as b
Remember them carefully, since we will need them in other parts of the tutorial.
Our loop does the following:
At first it checks wether the condition is true or false. If true, the code inside of the loop will be executed, if false, the loop will be cancelled. This way the loop repeats itself until the condition is not true anymore.
Tip: To create an infinite loop, use a while loop with
true
as condition. Since true always equals true, the loop will never cancel!
That was todays tutorial! In the next part, we will take a look at if-statements and how to use them. If you have any questions, ask them in the commentaries!