The "print" command outputs text directly to the screen, while the "return" command outputs the values back to whatever is calling the function.
For example:
- Code: Select all
def example():
print 1+1
example() # this will output the number 2 to the screen
- Code: Select all
def example():
return 1+1
x = example() # this will store the number 2 in the variable called x
I'm guessing the reason you get them confused is because of the way the Python command line works - if you had either of those functions set up and you just typed "example()" into the interpreter, it would display "2"... this is because if you type in an expression that returns some result, then the interpreter automatically displays that. So in the first case, typing "example()" makes it display "2" because that's what the example() function
does, and in the second case, typing "example()" makes it display "2" because that's what the function evaluates to, and then the interpreter displays that result.
In short: you use "print" in functions that are interacting directly with the user, to display information, and you use "return" in functions that need to pass its values back to other code.
As for your specific case... note that when it hits a "return" statement, it stops processing the function immediately, and sends back that value:
- Code: Select all
def example():
print "This is the start of the function"
return 5
print "This is after the return"
x = example() # this will display "This is the start of the function", and then store 5 in the variable x, but will *not* display "This is after the return"
So in your first code snippet, if you changed all the "print"s to "return"s, then it would only go as far as the first one (ie either "Alert: Cake Mode" or "Hey, you are not Alice") and not go any further. A function can only return one value... if you need a function to return many values, you need to bundle them up into a something like tuple, or a list, so all the values you need are packaged into a single object that you can return. But in this case, your Hello function is trying to interact directly with the user, so "print" is appropriate. While your verbing function is processing on a string that you will presumably want to use as a part of other code, so "return"ing that value makes more sense.