Use of loops with “while” and loops with “for”

--Originally published at Start in the world of the #TC101

Loops in Think Python

Loops with “for”

Python provides a clean iteration syntax. Note the colon and indentation.

Example

>> for i in range(0, 3):
>>     print(i*2)
0
2
4

Loops with “while”

A While loop permits code to execute repeatedly until a certain condition is met. This is useful if the number of iterations required to complete a task is unknown prior to flow entering the loop.

Syntax

while condition:
    //do something
>> looping_needed = True
>>
>> while looping_needed:
>>     # some operation on data
>>     if condition:
>>          looping_needed = False