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.

else:# Optional elseBasic ExamplesTo demonstrate, let’s look at a few simple examples of the if statement at work. Allparts are optional, except the initial if test and its associated statements; in the simplestcase, the other parts are omitted:>>> if 1:... print 'true'...trueNotice how the prompt changes to ... for continuation lines in the basic interfaceused here (in IDLE, you’ll simply drop down to an indented line instead—hit Backspaceto back up); a blank line terminates and runs the entire statement. Rememberthat 1 is Boolean true, so this statement’s test always succeeds. To handle a falseresult, code the else:>>> if not 1:... print 'true'... else:... print 'false'...falseMultiway BranchingNow, here’s an example of a more complex if statement, with all its optional partspresent:>>> x = 'killer rabbit'>>> if x == 'roger':... print "how's jessica?"... elif x == 'bugs':... print "what's up doc?"... else:... print 'Run away! Run away!'...Run away! Run away!This multiline statement extends from the if line through the else block. When it’srun, <strong>Python</strong> executes the statements nested under the first test that is true, or theelse part if all tests are false (in this example, they are). In practice, both the elif andelse parts may be omitted, and there may be more than one statement nested in eachsection. Note that the words if, elif, and else are associated by the fact that theyline up vertically, with the same indentation.if Statements | 237

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

Saved successfully!

Ooh no, something went wrong!