Tag Archives: while

Python: For and While Loop

So repetition on Python is very similar to other programming languages, you have the choice of a For and While loop.

For Loop

If you are familiar with foreach statement in C# then this will be easy to understand. Below I have a list of numbers from 1 to 5, then I use the for statement to get each number from numbers and print it.

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print number

While Loop

While loop code snippet below I have created a list of numbers from 1 to 5 and I have an index variable of 0. I will be using the index to iterate through the numbers list and at the same time I increment the index. The while loop will be validating if the index is less thanĀ 5, if it is true continue to print the number. If the index is greater than 5 exit out of the while loop.

numbers = [1, 2, 3, 4, 5]

index = 0

while index < 5:
    print numbers[index]
    index += 1

Download the source code for this blog from my GitHub repository: