[Tutor] Generic For Loop
alan.gauld at btinternet.com
Thu Oct 13 06:23:32 CEST 2011
On 13/10/11 01:41, Max S. wrote:
> I've been doing some research into C++, and I've noticed the for loops.
If you are trying to program in Python you should probably research
Python rather than C++. Any tutorial will provide information about for
> Is there a way to use the C++ version of the loops instead of the Python
> one? For example, I believe that the Python syntax would be:
> for a=1, a < 11, a += 1:
> print("Loop ended.")
for a in range(1,11): print( a )
> if the 'for' keyword did it's function as in C++, Actionscript, or most
> other programming languages. Is there a way to do this?
Of course, however...
Its generally better to think of the Python for lop as being a foreach
loop. It iterates over a collection.
The C style for loop is a much more primitive loop and is really just a
piece of syntactic sugar to implement a while loop:
a = 1
while a < 11:
a += 1
# loop body here
Because it is just a loosely disguised while loop you can put
arbitrarily complex expressions into it and to replicate those in Python
you need to use the while loop. But generally that kind of obfuscation
in C++ is better avoided anyway.
The Python style loop is much more powerful than C's in its ability to
iterate over lists, dictionaries, strings, files and any other iterable
object. C++ introduces iterators as a library class to address this and
enable foreach style processing, but at the expense of loop speed.
Author of the Learn to Program web site
More information about the Tutor