![]() |
![]() |
|
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
Last time, we saw how we can turn our code into functions, using “
One new concept: the function
Example:
print( "hello" ) print( "hi t" + "here") print( ruUserName("James Fallon") ) print( "Jimmy Fallon's name at RU is " + ruUserName("James Fallon") + ".") |
Note that
Example:
print( "The BMI of the penguin is dangerously high: " + str( bmi(220,3,3.2) ) ) |
Be aware:The
len( print("hello") ) . Moreover, ifruUserName had just printed its result (rather than return it), we couldn't even ever computelen( ruUserName( "Jay Leno" ) ) .In general, printing does not “play well with other functions”. Most functions should return their answer, and not print them; we'll wrap the “real” functions with code that prints out the results, when we want to see a particular result (as opposed to further-processing-the-result).
When you Load a program that is in the editor pane, and 'print' statements are discarded1.
But if you call a function from the interaction pane (bottom), any
# Editor pane: # ruUserName : string -> string # Return the RU username, for somebody with the given `fullName`. # def ruUserName( fullName ): firstInit = substring(fullName,0,1) startLast = string.find( fullName, " " ) + 1 # last-name starts 1 char *after* the space. lastName = substring(fullName, startLast, len(fullName)) return string.lower( firstInit + lastName ) # triple: float -> float # Triple a number. # def triple( x ): return x * 3 # tst : None -> None # Call/test the above function, printing some results. # def tst(): print( "user name for Walter Mitty: " ) print( "Expect: " + "wmitty" ) print( "Actual: " + ruUserName("Walter Mitty") ) print( "user name for Jay Z: " ) print( "Expect: " + "jz" ) print( "Actual: " + ruUserName("Jay Z") ) print( "bmi for the penguin -- 220lbs, 3ft 3.2in:") print( "Expect: " + str(100) + " (approx)" ) print( "Actual: " + str(bmi(220, 3, 3.2)) ) |
Your Task:
Add a
1More precisely, the editor pane does not have its own 'output window', and so all output is discarded. I wish that the interaction pane (bottom) served as the editor pane's output-terminal, but it doesn't, sigh. ↩
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
©2014, Ian Barland, Radford University Last modified 2014.Mar.31 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |
![]() |