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.

5.5. Alternative execution 41if statements have the same structure as function definitions: a header followed by an indentedbody. Statements likethisare called compound statements.Thereisnolimitonthenumberofstatementsthatcanappearinthebody,buttherehastobeatleastone. Occasionally, it is useful to have a body with no statements (usually as a place keeper for codeyou haven’t writtenyet). Inthat case, you can usethepassstatement, which does nothing.if x < 0:pass# need to handle negative values!5.5 AlternativeexecutionAsecondformoftheifstatementisalternativeexecution,inwhichtherearetwopossibilitiesandthecondition determines which one gets executed. The syntax looks likethis:if x%2 == 0:print 'x is even'else:print 'x is odd'If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displaysa message tothat effect. If the condition isfalse, the second set of statements is executed. Since theconditionmustbetrueorfalse,exactlyoneofthealternativeswillbeexecuted. Thealternativesarecalled branches, because they arebranches inthe flow of execution.5.6 Chained conditionalsSometimes there are more than two possibilities and we need more than two branches. One way toexpress acomputation likethat isachained conditional:if x < y:print 'x is less than y'elif x > y:print 'x is greater than y'else:print 'x and y are equal'elifisanabbreviationof“elseif.” Again,exactlyonebranchwillbeexecuted. Thereisnolimitonthe number of elif statements. If there is an else clause, it has to be at the end, but there doesn’thave tobe one.if choice == 'a':draw_a()elif choice == 'b':draw_b()elif choice == 'c':draw_c()Eachconditionischeckedinorder. Ifthefirstisfalse,thenextischecked,andsoon. Ifoneofthemistrue,thecorrespondingbranchexecutes,andthestatementends. Evenifmorethanoneconditionistrue, only thefirsttruebranch executes.

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

Saved successfully!

Ooh no, something went wrong!