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.

Because continue jumps to the top of the loop, you don’t need to nest the printstatement inside an if test; the print is only reached if the continue is not run. If thissounds similar to a “goto” in other languages, it should. <strong>Python</strong> has no goto statement,but because continue lets you jump about in a program, many of the warningsabout readability and maintainability you may have heard about goto apply.continue should probably be used sparingly, especially when you’re first gettingstarted with <strong>Python</strong>. For instance, the last example might be clearer if the print werenested under the if:x = 10while x:x = x-1if x % 2 == 0:print x,# Even? -- printbreakThe break statement causes an immediate exit from a loop. Because the code that followsit in the loop is not executed if the break is reached, you can also sometimesavoid nesting by including a break. For example, here is a simple interactive loop (avariant of a larger example we studied in Chapter 10) that inputs data with raw_input,and exits when the user enters “stop” for the name request:>>> while 1:... name = raw_input('Enter name:')... if name == 'stop': break... age = raw_input('Enter age: ')... print 'Hello', name, '=>', int(age) ** 2...Enter name:melEnter age: 40Hello mel => 1600Enter name:bobEnter age: 30Hello bob => 900Enter name:stopNotice how this code converts the age input to an integer with int before raising it tothe second power; as you’ll recall, this is necessary because raw_input returns userinput as a string. In Chapter 29, you’ll see that raw_input also raises an exception atend-of-file (e.g., if the user types Ctrl-Z or Ctrl-D); if this matters, wrap raw_input intry statements.elseWhen combined with the loop else clause, the break statement can often eliminate theneed for the search status flags used in other languages. For instance, the followingpiece of code determines whether a positive integer y is prime by searching for factorsgreater than 1:252 | Chapter 13: while and for Loops

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

Saved successfully!

Ooh no, something went wrong!