Search code examples
pythonfunctionreturncall

When is a function called/referred to and when is it being executed?


I'm relatively new to Python and I have a (I guess) pretty basic question on functions in Python.

I'm rewatching basics tutorials in order to really understand more of the structures and not just use them. I used some basic code from a tutorial and tried different simple variations and I don't fully understand the outcomes and when a function is being referred to, i.e. when its return value is being called for, and when it's being executed.

x=6

def example():

    globx = x
    print(globx)
    globx+=5
    print(globx)

example()

This defines the function and afterwards calls for it to be executed and as it's being executed it prints 6 and then prints 11, as expected.

Now:

x=6

def example():

    globx = x
    print(globx)
    globx+=5
    print(globx)

print(example())

I would have expected this to print "None" since print is looking for a return value of the function to print it but example() doesn't return a value. Instead 6, 11 and None are being printed. So I assume print(example()) calls for example()'s return value to print it but before also executes the function. (Please correct me if I got that wrong.).

Even when I'm just assigning the return value to a variable x = example() after the definition of the function, it will also execute the function and print 6 and then 11.

x=6

def example():

    globx = x
    print(globx)
    globx+=5
    print(globx)

x = example()

Is a function always being executed when it's written out? (Ecxcept in the def) Is there a way to make use of a functions return value without it being fully executed? For example if I had a more complex code and at some point I want to make use of a functions return value but don't want it to be run.

Thanks in advance!


Solution

  • What you say seems overall correct, even if it seems off what you expected.

    Generally, you can see it as, when the function has parentheses at the end, i.e. example(), the function is executed.

    Your last question is a bit vague, but you can stop executing the function at some point by using the return keyword inside the function. This makes sense in e.g. a function that performs some resource-intensive calculations, but occasionally there's a chance to take a shortcut.

    As an example

    def calculate_thing(shortcut = False):
        if shortcut:
            return 3
        # Resource-intensive, time-consuming calculations go here
        return result_of_calculations
    

    Calling this function with calculate_thing(shortcut=True) will quickly return 3, because the function stops executing when we hit return 3. On the other hand, calling it by calculate_thing(shortcut=False) or calculate_thing() (False is the default value for shortcut) will make the function run for a while, doing some calculations, and then it returns whatever value was assigned to the variable result_of_calculations.