12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Why You Will Care: Emulating C while LoopsThe section on expression statements in Chapter 11 stated that <strong>Python</strong> doesn’t allowstatements such as assignments to appear in places where it expects an expression.That means this common C language coding pattern won’t work in <strong>Python</strong>:while ((x = next( )) != NULL) {...process x...}C assignments return the value assigned, but <strong>Python</strong> assignments are just statements,not expressions. This eliminates a notorious class of C errors (you can’t accidentallytype = in <strong>Python</strong> when you mean ==). But, if you need similar behavior, there are at leastthree ways to get the same effect in <strong>Python</strong> while loops without embedding assignmentsin loop tests. You can move the assignment into the loop body with a break:while True:x = next( )if not x: break...process x...or move the assignment into the loop with tests:x = 1while x:x = next( )if x:...process x...or move the first assignment outside the loop:x = next( )while x:...process x...x = next( )Of these three coding patterns, the first may be considered by some to be the leaststructured, but it also seems to be the simplest, and most commonly used. (A simple<strong>Python</strong> for loop may replace some C loops as well.)The for statement also supports an optional else block, which works exactly as itdoes in a while loop—it’s executed if the loop exits without running into a breakstatement (i.e., if all items in the sequence have been visited). The break and continuestatements introduced earlier also work the same in a for loop as they do in a while.The for loop’s complete format can be described this way:for in :if : breakif : continueelse:# Assign object items to target# Exit loop now, skip else# Go to top of loop now# If we didn't hit a 'break'for Loops | 255

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

Saved successfully!

Ooh no, something went wrong!