On 9/28/07, James <[EMAIL PROTECTED]> 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
Here you're basing yourself off of the index of the item in the list, so stuff[0], stuff[1], etc. 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 ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] Here, you're using *for* in a non-Pythonic way. You mean to use i as an iterator, but len( stuff ) is a simple integer. You could do it this way: for i in range( len(stuff)): os.system( stuff[i] ) j = i + 1 print stuff[ j ] turning the single integer into a range of integers that you can iterate over. Tony R.
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor