Section 19.4 Common Function Issues
There are a few common mistakes you should watch out for while writing functions.
Subsection 19.4.1 Returning Ends a Function
One common mistake when writing functions is to try to do work after a return statement. When Python hits a return
, it does just that: it returns to the place the function was called. The program below tries to use the addFive
function to add 5 to the score; however, the code in the function that does the math comes after the return and thus never runs! Try running it in Codelens mode to see:
Subsection 19.4.2 Trying to Change a Parameter
The parameters for a function are variables that only exist inside of that function. You can make changes to their values, but doing so does not affect the rest of the program.
This version of the program does not work correctly either. score
is passed as the argument from the main part of the program into addFive
. That means addFive
uses a copy of score
’s value as its value for x
. But x
and score
are not linked in any way. A change to x
does nothing to change the value of score
. Nothing is ever returned, so the rest of the program never learns about the changes that happened in addFive
.
Again, try running in Codelens:
Check Your Understanding
Checkpoint 19.4.3.
The following program is supposed to convert a Celsius temp into Fahrenheit.
Put the blocks in the right order and indentation. As usual, you will not use all the blocks.
def convertCtoF(celsiusValue):
---
newTemp = (9 / 5) * celsiusValue
newTemp = newTemp + 32
---
celsiusValue = (9 / 5) * celsiusValue
celsiusValue = celsiusValue + 32 #distractor
---
return newTemp
---
return todaysTempF #distractor
---
todaysTempCelsius = 16
todaysTempF = convertCtoF(todaysTempCelsius)
print(todaysTempF)
You have attempted
of
activities on this page.