1
votes

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 var1'

def func1(): 
  return var1

print(func1())

Both give same result:

$ ./func_var_print_return.py
This is var1
3
print doesn't return values from a function! In this sense neither your question nor your example makes sense! try print func1() vs print func2(). (where your 2nd func1 Is func2!) But in all honestly in your example it doesn't really matter, because var1 is a "global" variable and stays the same regardless of the functions involved! - Don Question
@DonQuestion thanks for replay. This is just quik simple example, so - of course, here is no anything from IRL. - setevoy

3 Answers

2
votes

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

def add(x,y):
    return x + y

def multiply(a,b):
    product = 0
    for i in range(b):
        product = add(product, a)   # Note I am calling the add function
    return 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.

2
votes

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

1
votes

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.