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...
Return values from a function can even be substituted for variables anywhere in a program.
# define a function
if tall == 1 and dark == 1 and handsome == 1:
return "I'm sorry, I just don't feel the same way about
# set some variables
tall = 1
dark = 1
handsome = 1
# pop the question
print "Will you marry me?"
# use return value in a function call
Notice how the function is able to read the values of variables defined outside the function; this is related to variable scope in Python, and I plan to discuss it in detail a little further down.
Return values need not be numbers or strings alone - a function can just as easily return a list, dictionary or tuple, as demonstrated in the following example: