Loops: For loop, while loop


Code can be repeated using a loop. Lines of code can be repeated N times, where N is manually configurable. In practice, it means code will be repeated until a condition is met. This condition is usually (x >=N) but it’s not the only possible condition.

Python has 3 types of loops: for loops, while loops and nested loops.

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python

For loop

We can iterate a list using a for loop

#!/usr/bin/python
 
items = [ "Abby","Brenda","Cindy","Diddy" ]
 
for item in items:
    print(item)

Visualization of for loop:
for loop

The for loop can be used to repeat N times too:

#!/usr/bin/python
 
for i in range(1,10):
    print(i)

While loop

If you are unsure how many times a code should be repeated, use a while loop.
For example,

correctNumber = 5
guess = 0
 
while guess != correctNumber:
    guess = int(input("Guess the number: "))
 
    if guess != correctNumber:
        print('False guess')
 
print('You guessed the correct number')

Nested loops

We can combine for loops using nesting. If we want to iterate over an (x,y) field we could use:

#!/usr/bin/python
 
for x in range(1,10):
    for y in range(1,10):
        print("(" + str(x) + "," + str(y) + ")")

Nesting is very useful, but it increases complexity the deeper you nest.

Scope
Python range

21 thoughts on “Loops: For loop, while loop

  1. Sagi Sulimani - April 22, 2017

    Hi Frank.
    There is a little mistake in the “While loop” example. It should be:

        guess = int(input("Guess the number: "))

    Otherwise, the compiler will compare between string and integer, and ‘5’!=5.
    Except it – excellent!

    1. Frank - April 22, 2017

      Thanks Sagi!
      I’ve updated the article.