12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

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

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

42 Chapter 5. Conditionals and recursion5.7 NestedconditionalsOne conditional can also be nested within another. We could have written the trichotomy examplelikethis:if x == y:print 'x and y are equal'else:if x < y:print 'x is less than y'else:print 'x is greater than y'Theouterconditionalcontainstwobranches. Thefirstbranchcontainsasimplestatement. Thesecondbranch contains another if statement, which has two branches of its own. Those two branchesareboth simplestatements, although they could have been conditional statements as well.Although the indentation of the statements makes the structure apparent, nested conditionals becomedifficult toread very quickly. Ingeneral, itisagood idea toavoid them when you can.Logical operators often provide a way to simplify nested conditional statements. For example, wecan rewritethe following code using asingleconditional:if 0 < x:if x < 10:print 'x is a positive single-digit number.'The print statement is executed only if we make it past both conditionals, so we can get the sameeffect withtheandoperator:if 0 < x and x < 10:print 'x is a positive single-digit number.'5.8 RecursionIt is legal for one function to call another; it is also legal for a function to call itself. It may not beobviouswhythatisagoodthing,butitturnsouttobeoneofthemostmagicalthingsaprogramcando. For example, look at thefollowing function:def countdown(n):if n >> countdown(3)

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

Saved successfully!

Ooh no, something went wrong!