Print V Call V Return


#1

This is a general query, not related to any specific exercise.

I've completely finished the Python course and am now 70% of the way through it a second time. But I still am confused by functions, and specifically what printing, calling and returning them actually means.

Sometimes you don't need to call them (i.e. print, or return seems to do), sometimes returning before printing (or vice versa) breaks the whole code, sometimes not. And sometimes you have to keep the print statement all the way out left, and sometimes you need to nest it under the rest of your function.

I have no idea why any of these things happen.

Would love an explanation.


#2

Function call:

def speak():
    print "Hi"

speak() //FUNCTION CALL

When you return, your function automatically exits, so anything after will not be executed.

Printing just shows output in the console. :slight_smile:


#3

So return just tells python my function is over. It's basically like a 'full stop' in an english sentence?

Does print or FUNCTION CALL implicitly include this 'full stop'?

In terms of your example above, what exactly does calling the function do? And why don't you return it instead of calling it?

Cheers


#4

Calling your function just runs it in the code.

def speak():
    print "Hi"

speak() //FUNCTION CALL
print "Who are you?"
#Outputs:
#Hi
#Who are you?

No, with print your function will continue to execute until a return or the end of the function.

The function call just makes your function run.

You cannot "return it" because you can only return inside of a function.


#6