[Tutor] foreach loops
Jordan Greenberg
jordangreenberg at gmail.com
Tue Sep 12 07:44:33 CEST 2006
Christopher Spears wrote:
> Hmmm...Perl is probably a bad example. My apologies.
> I was thinking more along the lines of this:
>
> A C++ for loop:
>
> #include <iostream>
>
> using std::cout;
>
> int main() {
>
> for (int i = 0; i < 10; i++) {
> cout << i << "\n";
> }
>
> return 0;
> }
>
The same functionality can be provided using python for and the range()
function, like:
for i in range(0, 10):
print i
Though because of the way python works you don't need to use this type
of loop anywhere near as often as in other languages. For example in
java (and c++, but my c++ is so rusty I'm not going embarrass myself
trying to write an example) you're constantly doing things like looping
over an array:
public void main(String[] args) {
int[] foo;
/* then later after foo has been initialized to whatever: */
for (int i=0; i<foo.length; i++) {
System.out.println(foo[i]);
}
}
The equivalent code in python is much cleaner, after foo has been
initialized to whatever:
for each in foo:
print each
Hope this helps,
Jordan Greenberg
More information about the Tutor
mailing list