logo

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:
Python Programming Bootcamp: Go from zero to hero

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.

Download Python Exercises

BackNext

21 thoughts on “Loops: For loop, while loop


  1. 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.

  2. Ian
    - August 20, 2015

    For the driving example in the comments section, it makes more sense to put the drive() command, in the while loop, before getting new input for the variable, action. As the code stands now, when one enters “stop”, one sees “driving” as the output response. Switching the order of the statements in the while loop, just terminates the loop silently when “stop” is entered.

  3. Barry Peters
    - August 19, 2015

    Can you explain the drive ()? Thanks!

    1. Frank
      - August 19, 2015

      Sure, this is an example of a condition in a while loop. It may be that while you do not press the break in a car, the car keeps moving forward.

      #!/usr/bin/env python
       def drive():
      print("driving")
       action = "driving"
      while "stop" not in action:
      action = raw_input("What to do next?")
      drive()

      A while loops code continues to be executed until the condition is True.

  4. Ryan
    - August 5, 2015

    Do you have any examples of the continue/break statements that C-style languages have?

    1. Admin
      - August 6, 2015

      Hi Ryan, you can simply use the break keyword in Python.

      #!/usr/bin/env python
       x = 0
      while True:
      print(x)
        if x == 10:
      break
        x = x + 1

      And example of continue:

      #!/usr/bin/env python
       x = 0
      while True:
        # use break to end the loop
      if x == 10:
      break
        x = x + 1
        # use continue to skip
      if x >= 3 and x <= 6:
      continue
        print x

  5. Ron Hall
    - June 17, 2015

    I notice that the loops terminate without executing for the last value (10 in your example). Also, how do you control the number of statements executed by the loop? There don’t seem to be any block boundaries.

    1. Frank
      - June 18, 2015

      Hi Ron, That’s correct, the parameters of range() are: range(start, stop[, step]) or range(start, stop). If you want to have 1 to 10, use range(1, 11).
      To define block boundaries you use 4 spaces. This applies for functions, loops, conditonal statements etc. The way we define the for loop is equivalent to C/C++ for (i = 1; i < 10; i++). I hope you enjoy the site 🙂

      1. Ben
        - August 19, 2015

        Hi Frank, How about a-z? I wrote range (a,z), it showed me “name ‘a’ is not defined”

        1. Frank
          - August 19, 2015

          Hi Ben, there are several ways to iterate through a character set:

          #!/usr/bin/python
           for x in range(ord('a'), ord('z')+1):
          print chr(x)

          or:

          #!/usr/bin/python
           x = "abcdefghijklmnopqrstuvwxyz"
           for i in range(0,len(x)):
          print(x[i])

          or

          #!/usr/bin/python
          from string import ascii_lowercase
           for i in ascii_lowercase :
          print(i)

          I hope that helps 🙂

          1. Michael
            - August 21, 2015

            nice examples thx .

            1. Frank
              - August 22, 2015

              Thanks! I’m happy you enjoy the site

          2. Ben
            - August 27, 2015

            Thank you so much

  6. Daniel Dauda
    - May 22, 2015

    simple and understandable examples. thanks

Leave a Reply

Login disabled