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.

x = y / 2 # For some y > 1while x > 1:if y % x == 0:# Remainderprint y, 'has factor', xbreak# Skip elsex = x-1else:# Normal exitprint y, 'is prime'Rather than setting a flag to be tested when the loop is exited, insert a break where afactor is found. This way, the loop else clause can assume that it will be executedonly if no factor was found; if you don’t hit the break, the number is prime. *The loop else clause is also run if the body of the loop is never executed, as youdon’t run a break in that event either; in a while loop, this happens if the test in theheader is false to begin with. Thus, in the preceding example, you still get the “isprime” message if x is initially less than or equal to 1 (e.g., if y is 2).More on the loop else clauseBecause the loop else clause is unique to <strong>Python</strong>, it tends to perplex some newcomers.In general terms, the loop else provides explicit syntax for a common codingscenario—it is a coding structure that lets you catch the “other” way out of a loop,without setting and checking flags or conditions.Suppose, for instance, that you are writing a loop to search a list for a value, and youneed to know whether the value was found after you exit the loop. You might codesuch a task this way:found = Falsewhile x and not found:if match(x[0]):print 'Ni'found = Trueelse:x = x[1:]if not found:print 'not found'# Value at front?# Slice off front and repeatHere, we initialize, set, and later test a flag to determine whether the search succeededor not. This is valid <strong>Python</strong> code, and it does work; however, this is exactlythe sort of structure that the loop else clause is there to handle. Here’s an elseequivalent:while x:if match(x[0]):# Exit when x empty* More or less. Numbers less than 2 are not considered prime by the strict mathematical definition. To bereally picky, this code also fails for negative and floating-point numbers and will be broken by the future /“true division” change described in Chapter 5. If you want to experiment with this code, be sure to see theexercise at the end of Part IV, which wraps it in a function.break, continue, pass, and the Loop else | 253

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

Saved successfully!

Ooh no, something went wrong!