More Flow Control
return, raise
The University of 1
Copyright By PowCoder代写 加微信 powcoder
Functions: What we know so far from W3?
– Functions allows you to refer to a set of instructions by its (function) name. There are four parts to each function:
– Thefunction (whatit’scalled)
– Thefunction (theinformation/variableswepassit). – Thereturntype(whatkindofthingisreturnedbythefunction). – Thefunctionbody(theactualcodethatdoesthework)
– Codes inside the function body will only execute during a function call.
– Can have none, one or many arguments. We can also have keyword
arguments e.g. sep and end in print() function. – Function scope matters. Consequences:
– Localvariablesinsidethefunctionscannotbeusedoutsidethefunctionunless returned as a return-value.
– GlobalvariablescanbeseenandusedinsidePythonfunctionbutyoucannot modify them.
The University of 2
Functions: What we know so far from W6?
– Stringsandtuplesareimmutable.Listsaremutable.
– Wecanpasslistsandtuplesasargumentsintoafunction.
– Two ways of passing arguments into the function:
– Pass by value:
• Acopyoftheargumentispassedtothefunction.
• Modificationtothevalueinsidefunctiondoesnotaffectoriginalcopy.
– Pass by reference:
• Memory address of the argument is passed to the function.
• Modificationtothevalueinsidethefunctionaffectsoriginalcopy.
– Wecanreturnalistoutoffunctionsbuttuplesare preferred to prevent modification of the result!
The University of 3
Revisit: return
– Review the codes given in Ed Lesson.
– What is the output of the program?
The University of 4
Revisit:return Observations
– Thereturnstatementwillalwaysreturnsomething(type
None) even if there is no explicit return statement.
– YoucanonlyreturnONEdatatype. – my_func() returns None
– my_func2()returnsstr
– return statements return a value and terminates the execution of the function. Hence, codes inside the function body after a return statement will not execute.
– There can be multiple return statements in a function.
The University of 5
return Multiple Values – Review the codes in demo.py.
– Whatisthedatatypeofthereturnvalue?
The University of 6
Premature return
– Inyouropinion,shouldthefunctionexecuteiftheargument
types are not int or float?
– Modify the codes to check if x and y are of type int or float. If they are not, return None.
– Howdoyoutestthetypeofanobject?
• RecallL2,everythinginPythonisanobject.type()functionreturnsthe
class of the object.
• Another function to check whether an object is an instance of a given class,
isinstance(). Run codes in Part 2.
– Whereshouldyouputthecodesforchecking?
• Typecheckingshouldbedoneatthestartofthefunctionbeforeany actions happen!
The University of 7
raise statement
– Wait, why don’t we stop execution completely and inform the programmer that something is wrong?
– raise keyword : Manually raise an exception
–
raise
general Exception
– Errormessageonterminal:
– Ed Lesson. Un-comment the function call one at a time in demo.py and run the program. Identify the line number that raises:
– Ageneralexception?
– AValueErrorexception?
The University of 8
Handling Exceptions: try…except
– Whatifwedon’twanttheprogramtostopexecutingbut
display a useful error message?
– Wecanmakeourprogramshandleexceptionsgracefullyusing
try and except. – Syntax:
try:
– Review try_demo.py in Ed Lesson. Step through the codes in VS Code and observe the Variables during execution.
The University of 9
Handling Exceptions: try…except
– Put codes where you suspect an error may occur into the try block.
– Theexceptblockwillonly execute when an exception occurs.
– The general except block must be placed at the bottom.
The University of 10
Summary: Multiple returns and return values
– Multiple return statements
– Checkallreturnpathwaysarecorrect.
– Ifperformingprematurereturnfortypechecking,makesurethe condition is correct.
– Multiple return values
– Tuplesarepreferredreturntypesoverlisttopreventunwanted
modification of the result (output) produced by the function.
– Theelementsarestoredaccordingtosequencethereturnvaluesare listed in the comma-separated list.
– Wecanunpacktheelementsintomultiplevariablesafteritispassed out of the function. Do this Ed Lesson.
The University of 11
Summary: break, continue, return, raise
Immediate exit from the loop.
Skip the current iteration of the loop, and go on to the next iteration.
Return a value and terminate function. Codes below the return statement will not execute.
Raise an exception to stop execution in extraordinary(rare) situations.
Body of loops
Body of loops
Body of functions and methods.
Special occasions – when exceptional events happen.
The University of 12
Summary – Exception Handling
– try a piece of code that contains potential rare error
– If the rare error occurs a new exception is generated. raise
– Theexceptioniscaughtusingexceptandhandled
– Following the try, error or not, more code can be executed with a block finally.
The University of 13
Reading This Week
– Chapter12.Tuplesasreturnvalues.Downey,A.B.(2015). Think Python: How to Think Like a Computer Scientist (2e ed.). O’ , Incorporated.
– Chapter2.1.Passingargumentsandreturningvalues. Sedgewick, R., Wayne, K., & Dondero, R. (2015). Introduction to programming in Python: An interdisciplinary approach. Addison- .
The University of 14
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com