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.

General FormatIn its most complex form, the while statement consists of a header line with a testexpression, a body of one or more indented statements, and an optional else partthat is executed if control exits the loop without a break statement being encountered.<strong>Python</strong> keeps evaluating the test at the top, and executing the statementsnested in the loop body until the test returns a false value:while :else:Examples# Loop test# Loop body# Optional else# Run if didn't exit loop with breakTo illustrate, let’s look at a few simple while loops in action. The first, which consistsof a print statement nested in a while loop, just prints a message forever. Recallthat True is just a custom version of the integer 1, and always stands for a Booleantrue value; because the test is always true, <strong>Python</strong> keeps executing the body forever,or until you stop its execution. This sort of behavior is usually called an infinite loop:>>> while True:... print 'Type Ctrl-C to stop me!'The next example keeps slicing off the first character of a string until the string isempty and hence false. It’s typical to test an object directly like this instead of usingthe more verbose equivalent (while x != '':). Later in this chapter, we’ll see otherways to step more directly through the items in a string with a for loop. Notice thetrailing comma in the print here—as we learned in Chapter 11, this makes all theoutputs show up on the same line:>>> x = 'spam'>>> while x: # While x is not empty... print x,... x = x[1:] # Strip first character off x...spam pam am mThe following code counts from the value of a up to, but not including, b. We’ll seean easier way to do this with a <strong>Python</strong> for loop and the built-in range function later:>>> a=0; b=10>>> while a < b: # One way to code counter loops... print a,... a += 1 # Or, a = a + 1...0 1 2 3 4 5 6 7 8 9while Loops | 249

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

Saved successfully!

Ooh no, something went wrong!