Loops: For loop, while loop

A piece of code can be repeated using a loop. A loop repeats a set of instructions N times. Python has 3 types of loops.

Video: Loops Get PDF Get Exercises Quiz

For loop

We can iterate a list using a for loop

items = [ "Abby","Brenda","Cindy","Diddy" ]
for item in items:

Visualization of for loop:
for loop

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

for i in range(1,10):

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 = 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:

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.

19 thoughts on “Loops: For loop, while loop

  1. Prashant Raina - January 28, 2016

    whats wrong with this code not generating primes as i expected

    num=int(input("enter the no. upto which u want the primes: "))
    while i<num:
        while j<len(arr):
            if i%arr[j]==0:
                print i
    1. Frank - January 30, 2016

      The conditions in the while loops are never true. I fixed your code:

      num=int(input("enter the no. upto which u want the primes: "))
      i = 2
      while max(arr) < num:
         prime = True
         for p in arr:
             if i % p == 0:
                 prime = False
         if prime:
         i = i + 1  

      You can see the prime numbers being added to the array in the loop.

  2. Deepak V a - December 3, 2015

    why are you using str() in print statement i am getting even i used variable directly

    1. Frank - December 3, 2015

      sometimes that may lead to problems as they have different datatypes,just being cautious.

  3. Amina Khatun - August 31, 2015

    From where I should start I can’t understand? How to save, How to edit, How to run, These are my problems.

    1. Frank - August 31, 2015

      Hi Amina, start from here: https://pythonspot.com/getting-started/
      Download an editor like PyCharm to edit, save and run your code.