Howdy, Stranger!

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

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Python for loop

pietersieliepietersielie Posts: 2Member
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

  • bubbatremellbubbatremell Posts: 39Member
    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!

  • pietersieliepietersielie Posts: 2Member
    Thanks very much
Sign In or Register to comment.