This week, Python 101 discusses how to abstract out parts of yourPython code into reusable functions, add flexibility to them by allowingthem to accept different arguments, and make them return specific values.Also included: a discussion of variable scope and functions to help youwrite your own functions. Confused? All is explained within...
Usually, when a function is invoked, it generates a "return value". This return value is either a built-in Python object called "None", or a value explicitly returned via the "return" statement. I'll examine both these a little further down - but first, here's a quick example of how a return value works.
#!/usr/bin/python
# define a function
def tempConv():
celsius = 35
fahrenheit = (celsius * 1.8) + 32
return fahrenheit
# assign return value to variable
result = tempConv()
print "35 Celsius is", result, "Fahrenheit"
The output is:
35 Celsius is 95.0 Fahrenheit
In this case, the value of the last expression evaluated within the function is assigned to the variable "result" when the function is invoked from within the program. Note that the return value must be explicitly specified within the function definition via the "return" statement; failure to do so will cause the function to return a null object named "None".
To illustrate this, consider the output if the "return" statement is eliminated from the function definition above.