In the examples we used before , sometimes it was required to do the same work couple of times. We use a counter to check how many times the code needs to be executed. This technique is known as looping. First we are going to look into while statement for looping.
The syntax for
while statement is like
while condition:
statement1
statement2
The code we want to reuse must be indented properly under the while statement. They will be executed if the
condition is true. Again like in
if-else statement any non zero value is true. Let us write a simple code to print numbers 0 to 10
>>> n = 0
>>> while n < 11:
... print n
... n += 1
...
0
1
2
3
4
5
6
7
8
9
10
In the first line we are setting
n = 0, then in the while statement the condition is
n < 11 , that means what ever line indented below that will execute until n becomes same or greater than 11. Inside the loop we are just printing the value of n and then increasing it by one.