For Loop

It’s time for an awesome part of Python. Python’s for loops are pretty amazing compared to some other languages because of how versatile and simple they are. The idea of a for loop is rather simple, you will just loop through some code for a certain number of times. I won’t get a chance to show you the flexibility of the for loops until we get into lists, but sure enough its time will come. Onto an example:

Example

Result

1
2

First, print is indented for a reason. Remember that Python is picky about spacing. It is somewhat complicated to understand exactly what a is in the example. In this instance, a is a variable the increments itself every time we run through the loop. Next, we use the range keyword to set the starting point and the point right after we would finish. This is precisely why the number 3 didn’t print. Python is quite fond of this idea of all the way up to a number, but not including it.

Also, notice the in keyword. This is actually part of the for loop and you will understand it a bit better after we deal with lists and dictionaries. So, basically the above for loop says, “For variable a, which will be incremented at the end of every loop, in the range of 1 up to 3.”

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

  1. In python version 3.3 not work. Just info 🙂
    Hmm, or maybe is another way ..

    But we have using,
    example :

    word = [1,2,3]

    for x in word:
    print(x)

    result :

    1
    2
    3

    Thanks alot for your tutorial, i amvery happy with your article about Python Programming ..

  2. After print statement does the for loop ends? What if the multiple statements have to be written inside the loop?? Some one please give some perfect example

  3. @kumar : for-loop will execute all indented lines after it, until the indentation changes.
    Try out this example:

    for e in range(1, 5):
    print "inside loop"
    print "loop " + str(e)
    print 2 ** e
    print 3 ** e
    print "not inside loop"
    print 2 ** 10

  4. For me this is is so far the best tutorial ever, I’ve only done a little bit of programming before and I’m picking this all up so easily!

  5. Thanks Daniel! Tried out your suggestion!
    @kumar : for-loop will execute all indented lines after it, until the indentation changes.
    Try out this example:

    for e in range(1, 5):
    print "inside loop"
    print "loop " + str(e)
    print 2 ** e
    print 3 ** e
    print "not inside loop"
    print 2 ** 10

  6. @Nourequip

    look at this example

    for a in range(1,3):
    print (a)
    b=a+10
    print(b)
    print (" for loop finished")

    Everithing that it’is spaced it’is under the "for" function.
    Hope this will solve your dubts

  7. agreed. Also, try :
    for i in range(501)
    print i
    print i

    if you want your computer to lag out…. Choose wisely!

  8. And mathkindaguy, did you learn all that programming from the previous tutorials?! Because i didn’t even get close to that! 😀

  9. range are easily understoood i love it heree.check out my own crazy test on def function

    male = "richard"
    female= "alicia"
    def name():
    print (male, female)
    name()

  10. Happy that we dont have to increment the loop variable
    a=10
    for a in range(10,20):
    print(a)
    #a=a+1
    print("–")

    print(a)

  11. Also we can increment the loops , in the below example i am increment the loop by 5

    for a in range(10,30,5):
    print(a)

  12. For loop doesn’t really work like you described here. Try this:
    print(range(1,3))
    You get:
    [1,2]
    So:
    for a in range(1,3):
    print(a)
    Means:
    for each value (we’ll call it ‘a’) in range(1,3) (which is the list [1,2]):
    print the variable ‘a’

    This would look better done in colours, but I hope you see what I’m trying to say.

  13. for a in range(1,99999):
    Print (a)

    Right then was when i had to restart my laptop after about an hour.
    (Not using the internet python tester)

  14. Just wanted to share couple of things about for loops, what happens if you intentionally ( or not ) put an error.

    if you do not include the colon at the end of if statement in that same line – then you get a parse error as follows-

    ParseError: bad input on line1

    Also, I included in my code an intentional indentation error: and the message you get is:

    >>> code

    for a in range(1,3):
    b = a
    print (b)

    code <<<<

    Error message –
    File ".py", line 3 print (b) ^ IndentationError: unindent does not match any outer indentation level

    ******************** Now the interesting error. Should the last line have an intentional error after indentation spaces — the error changes –

    >>>code
    for a in range(1,3):
    b = a
    print (b)
    <<< code

    error message –

    ParseError: bad input on line3

    ========================= That to me sounded *** WWWhhhaat! LOL

  15. By adding a module statement we can print even numbers.Just do as the following:

    for a in range(1, 20):
    if a%2==0: #This is were we add the module
    print (a)

  16. Im starting to get this, grate explenations

    b=1
    for a in range(1,6):
    print(a)
    if b>9000:
    print(“IT’S OVER 9000!!!”)
    else:
    print(“not yet…”)
    print(b)
    b*=10

  17. I apologise for the fibonacci test on your server

    def a(b):
    if n < 2: return n return a(b-2) + a(b-1) print map(a, range(startNumber, endNumber)) I didn't mean to cause a problem. I plugged in 1 and then a few 9's, it was an experiment. where can i download a python writing program please.

  18. There is a typo in the third sentence of the second paragraph: “In this instance, a is a variable the increments itself every time we run through the loop.” It should be “? a variable *that* increments ?”

  19. print(str(range(1,9)));

    to know the element of the “range(x,y)”, without going thru a loop. Coming from C/C++, it’s NOT something you can do in a 1 liner !! well done python

  20. how to get every other element? i.e. skipping even index elements in a list.
    for example in the list [0,1,2,3,4,5,6,7,8], i only want to work on the 0,2,4,6,8 ?

  21. Not including the last number seems inelegant. There must be a reason its done that way. Anyone know why?

    (1,3)-> 1,2,3 seems more elegant or logical than (1,2)

  22. Perhaps at least half of all readers may be wondering why after each lesson there’s a plug for a book, but no mention of it’s name, no link… just a mystery. Perhaps Author can explain?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.