12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Although such range results may be useful all by themselves, they tend to come inmost handy within for loops. For one thing, they provide a simple way to repeat anaction a specific number of times. To print three lines, for example, use a range togenerate the appropriate number of integers:>>> for i in range(3):... print i, '<strong>Python</strong>s'...0 <strong>Python</strong>s1 <strong>Python</strong>s2 <strong>Python</strong>srange is also commonly used to iterate over a sequence indirectly. The easiest andfastest way to step through a sequence exhaustively is always with a simple for, as<strong>Python</strong> handles most of the details for you:>>> X = 'spam'>>> for item in X: print item, # Simple iteration...s p a mInternally, the for loop handles the details of the iteration automatically when usedthis way. If you really need to take over the indexing logic explicitly, you can do itwith a while loop:>>> i = 0>>> while i < len(X): # while loop iteration... print X[i],; i += 1...s p a mBut, you can also do manual indexing with a for, if you use range to generate a list ofindexes to iterate through:>>> X'spam'>>> len(X) # Length of string4>>> range(len(X)) # All legal offsets into X[0, 1, 2, 3]>>>>>> for i in range(len(X)): print X[i], # Manual for indexing...s p a mThe example here is stepping over a list of offsets into X, not the actual items of X; weneed to index back into X within the loop to fetch each item.Nonexhaustive Traversals: rangeThe last example in the prior section works, but it probably runs more slowly than ithas to. It’s also more work than we need to do. Unless you have a special indexingrequirement, you’re always better off using the simple for loop form in <strong>Python</strong>—use266 | Chapter 13: while and for Loops

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!