Example 9: Converting a for-loop into a while loop

Iterate over a String.

For loop version:

str = 'Python'
for letter in str:
    print letter

While loop version:

str = 'Python'
i = 0
while i < len(str):
    print str[i]
    i = i+1

In the for-loop we don’t need the index variable to iterate over the string, while in the while loop we use the variable i as the index for the string. We first initialize the variable i and set it to 0. Then, every time when the loop is executed, the variable i is increased by 1 until it reaches the last index.