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.

B RAINB UILDERChapter Quiz1. When is a loop’s else clause executed?2. How can you code a counter-based loop in <strong>Python</strong>?3. How are for loops and iterators related?4. How are for loops and list comprehensions related?5. Name four iteration contexts in the <strong>Python</strong> language.6. What is the best way to read line by line from a text file today?7. What sort of weapons would you expect to see employed by the SpanishInquisition?Quiz Answers1. The else clause in a while or for loop will be run once as the loop is exiting, ifthe loop exits normally (without running into a break statement). A break exitsthe loop immediately, skipping the else part on the way out (if there is one).2. Counter loops can be coded with a while statement that keeps track of the indexmanually, or with a for loop that uses the range built-in function to generatesuccessive integer offsets. Neither is the preferred way to work in <strong>Python</strong>, if youneed to simply step across all the items in a sequence—use a simple for loopinstead, without range or counters, whenever possible. It will be easier to code,and usually quicker to run.3. The for loop uses the iteration protocol to step through items in the objectacross which it is iterating. It calls the object’s next method on each iteration,and catches the StopIteration exception to determine when to stop looping.4. Both are iteration tools. List comprehensions are a concise and efficient way toperform a common for loop task: collecting the results of applying an expressionto all items in an iterable object. It’s always possible to translate a listcomprehension to a for loop, and part of the list comprehension expressionlooks like the header of a for loop syntactically.5. Iteration contexts in <strong>Python</strong> include the for loop; list comprehensions; the mapbuilt-in function; the in membership test expression; and the built-in functionssorted, sum, any, and all. This category also includes the list and tuple built-ins,string join methods, and sequence assignments, all of which use the iteration protocol(the next method) to step across iterable objects one item at a time.276 | Chapter 13: while and for Loops

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

Saved successfully!

Ooh no, something went wrong!