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.

40 Chapter 5. Conditionals and recursion>>> type(True)>>> type(False)The==operator isone of therelational operators; theothers are:x != yx > yx < yx >= yx 0 and x < 10 is true only if x is greaterthan 0and lessthan 10.n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisibleby 2or 3.Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false,that is,ifxisless thanor equal toy.Strictlyspeaking,theoperandsofthelogicaloperatorsshouldbebooleanexpressions,but<strong>Python</strong>isnot very strict. Any nonzero number isinterpreted as“true.”>>> 17 and TrueTrueThis flexibility can be useful, but there are some subtleties to it that might be confusing. You mightwant toavoid it(unless you know what you are doing).5.4 Conditional executionInordertowriteusefulprograms,wealmostalwaysneedtheabilitytocheckconditionsandchangethe behavior of the program accordingly. Conditional statements give us this ability. The simplestform istheifstatement:if x > 0:print 'x is positive'Thebooleanexpressionaftertheifstatementiscalledthecondition. Ifitistrue,thentheindentedstatement gets executed. Ifnot, nothing happens.

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

Saved successfully!

Ooh no, something went wrong!