《Py4Inf-03-Conditional-PrintPy4Inf-03-Conditional-Print》由会员分享,可在线阅读,更多相关《Py4Inf-03-Conditional-PrintPy4Inf-03-Conditional-Print(8页珍藏版)》请在金锄头文库上搜索。
1、Conditional ExecutionChapter 3Python for Informatics: Exploring IUnless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License.htp:/creativecommons.org/licenses/by/3.0/.Copyright 2010- Charles R. SeveranceConditional StepsOutput:SmalerFinisP
2、rogram:x = 5if x 20: print Bigerprint Finisx = 5X 20 ?print Bigerprint FinisYesYesComparison OperatorsBoolean expressions ask a question and produce a Yes or No result which we use to control program flowBoolean expressions using comparison operators evaluate to - True / False - Yes / NoComparison o
3、perators lok at variables but do not change the variableshttp:/en.wikipedia.org/wiki/George_BooleRemember: “=” is used for asignment.Python Meaning= Greater than or Equal Greater than!= Not equalComparison Operatorsx = 5if x = 5 : print Equals 5if x 4 :print Greater than 4if x = 5 :print Greater tha
4、n or Equal 5if x Preferences - Language Menu/Tab SettingsTextWrangler: TextWrangler - Preferences - Editor DefaultsPython cares a *lot* about how far line is indented. If you mix tabs and spaces, you may get “indentation errors” even if everything loks finePlease do this now while you are thinking a
5、bout it so we can al stay sane.This wil save you much unnecessary pain.x = 5if x 2 :print Biger than 2print Stil bigerprint Done with 2for i in range(5) :print iif i 2 : print Biger than 2print Done with i, ix = 5if x 2 :# commentsprint Biger than 2# dont matterprint Stil biger# but can confuse youp
6、rint Done with 2# if you dont line # them upincrease / maintain after if or fordecrease to indicate end of blockblank lines and comment lines ignoredMental begin/end squaresx = 5if x 2 :print Biger than 2print Stil bigerprint Done with 2for i in range(5) :print iif i 2 : print Biger than 2print Done
7、 with i, ix = 5if x 2 :# commentsprint Biger than 2# dont matterprint Stil biger# but can confuse youprint Done with 2# if you dont line # them upx 1print More than onex 1 :print More than oneif x 1print More than onex 1 :print More than oneif x 1print More than onex 1 :print More than oneif x 2prin
8、t BigeryesnoX = 4print Not bigerprint All DoneTwo-way using else :x = 4if x 2 :print Bigerelse :print Smalerprint All donex 2print BigeryesnoX = 4print Smalerprint All DoneTwo-way using else :x = 4if x 2 :print Bigerelse :print Smalerprint All donex 2print BigeryesnoX = 4print Smalerprint All DoneMu
9、lti-wayif x = 2 : print Two or moreelse :print Something elseWhich wil never print?The try / except StructureYou surround a dangerous section of code with try and except.If the code in the try works - the except is skippedIf the code in the try fails - it jumps to the except section$ cat notry.py as
10、tr = Hello Bobistr = int(astr)print First, istrastr = 123istr = int(astr)print Second, istr$ python notry.py Traceback (most recent cal last):File notry.py, line 2, in istr = int(astr)ValueError: invalid literal for int() with base 10: Hello BobThe program stops hereAllDoneSoftwareInputDevicesCentra
11、lProcessingUnitMainMemoryOutputDevicesSecondaryMemoryGenericComputer$ cat tryexcept.py astr = Hello Bobtry:istr = int(astr)except:istr = -1print First, istrastr = 123try:istr = int(astr)except:istr = -1print Second, istr$ python tryexcept.py First -1Second 123When the first conversion fails - it jus
12、t drops into the except: clause and the program continues.When the second conversion succeeds - it just skips the except: clause and the program continues.try / exceptastr = Bobastr = Bobtry:print Helloistr = int(astr)print Thereexcept:istr = -1print Done, istrprint Helloprint Thereistr = int(astr)p
13、rint Done, istristr = -1Safety netSample try / except$ python trynum.py Enter a number:42Nice work$ python trynum.pyEnter a number:fourtytwoNot a number$rawstr = raw_input(Enter a number:)try: ival = int(rawstr)except: ival = -1if ival 0 : print Nice workelse: print Not a numberExerciseRewrite your
14、pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours.Enter Hours: 45Enter Rate: 10 Pay: 475.0475 = 40 * 10 + 5 * 15ExerciseRewrite your pay program using try and except so that your program handles non-numeric input gracefully.Enter Hours: 20 Enter Rate: nin
15、e Error, please enter numeric inputEnter Hours: forty Error, please enter numeric inputSummaryComparison operators = = !=Logical operators: and or notIndentationOne Way DecisionsTwo way Decisions if : and else :Nested DecisionsMultiway decisions using elifTry / Except to compensate for errorsShort circuit evaluations