James wrote: > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 > > The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. > > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > Try this: > for i in range(len(stuff)): > > > > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > Python doesn't like it, though. It gives me the following error: > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. > > Thoughts/ideas appreciated. :) > for expects, as the error says, an "iterable". range() provides an iterable. len() just gives an integer.
BTW I find it very hard to read code where there are spaces next to () and []. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor