Skip to content Skip to sidebar Skip to footer

Using Functions: Print Vs Return

What is correct way to use data from functions in Python scripts? Using print, like: var1 = 'This is var1' def func1(): print(var1) func1() Or - with return: var1 = 'This is v

Solution 1:

You should return a value when the purpose of the function is to produce a value. This is so functions can use other functions. For example

defadd(x,y):
    return x + y

defmultiply(a,b):
    product = 0for i inrange(b):
        product = add(product, a)   # Note I am calling the add functionreturn product

Testing

>>>multiply(5,4)
20

Note that I used the return value from add within my multiply function. If I only printed the value from add, I would have been unable to do that.

Solution 2:

It depends on the situation. In general I would return it so you can print if you want but if you code changes at some point you can perform other operations with the value

Solution 3:

You should always try to return the value.

Think of unit tests -> How would you verify the value if it's not returned? And as mentioned by "meto" before, if your code changes you can still perform other operations with the value.

Post a Comment for "Using Functions: Print Vs Return"