Product SiteDocumentation Site

Chapter 6. Looping

6.1. While loop
6.2. Fibonacci Series
6.3. Power Series
6.4. Multiplication Table
6.5. Some printing * examples
6.6. Lists
6.7. For loop
6.8. range() function
6.9. Continue statement
6.10. Else loop
6.11. Game of sticks

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.

6.1. While loop

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.