Python for loop

Hey all

I have read the tutorial for the for loop in python plenty of time but still can't get it. I know pascal, php, javascript and their for loops are like this(php,javascript) for(i = 0; i < 10 ; i++) which I understand but can someone please help me to understand the for loop of python better.


Thank you

Comments

  • Well, I suppose it goes something like this:
    for x in a:
    #do stuff
    #next block
    I trust your problem doesn't involve the syntax or the whitespace rules, so I'll skip that. If I remember correctly, a is any iterable object (ie, lists, tuples, dictionaries, possibly strings). The loop is going to stick every item in a into x and run the code using that value for x. Here's an example:

    In [1]: a = ['red', 'blue', 'yellow', 'green']
    In [2]: for x in a:
    ...: print x
    red
    blue
    yellow
    green

    line 2 iterated over a, so x got each individual value in a. I don't quite remember how that goes in c++, but it would be something roughly like this:

    char a[] = {'c', 'd', 'e'};
    for(x=0; x<3; x++){
    cout<<a[x];
    }
    I think you can do it like that...
    Some other notes:
    -If you are iterating over a list of tuples, you can do something like this to easily get both elements in the pair:
    t = {'a':1, ...}
    for a,b in t.items():
    #stuff w/ a and other stuff w/ b
    That's great for dealing with dictionaries.
    -If you really need to iterate over a range of values (in the same way that you are used to), you can put range(start, end, [step]) to get the same effect.
    Hope that helps out!

  • Thanks very much
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories