Python

Moderators: None (Apply to moderate this forum)
Number of threads: 473
Number of posts: 1172

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Python for loop Posted by pietersielie on 13 Dec 2008 at 2:34 AM
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
Report
Re: Python for loop Posted by bubbatremell on 15 Dec 2008 at 4:04 PM
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!

Report
Re: Python for loop Posted by pietersielie on 16 Dec 2008 at 11:52 AM
Thanks very much



 

Recent Jobs