Return command clarification

Hello! I was just wondering about the return keyword when you use a function in python.

I understand that when you return a value in a function, that value can be saved as a variable. However, can variables be defined only by the values from a return statement?

For example, lets say I have this funciton:

def test_function(test_word)

could I save the test_word as a variable? This is very basic and I’m new at Python so I may have the incorrect syntax, or not know about something I will learn down the road! But I would like to know if values in a functions return statement are the only things in a function that can be stored in a variable! Thanks.

Hello @terasolver28052. When you return something from a function, it hands the data back to the caller. So, yes, you could store the result of a function’s return to a variable:

def some_function():
  return 3
some_var = some_function
print(some_var)#will print 3, as that was what was returned from the function.

You can store data in variables inside the function:

def a_func():
   var = 3

This will print 3. Here is an article explaining variables inside and outside of functions, and how to use them

The only way you can store data from a function in a variable is if that function has the return keyword:

def a_fun():
    a_var = 3
another_var = a_fun()
print(another_var)#will print None, since there is nothing returned from
#the function, and therefore nothing to store in a variable

I hope this helps!

Okay, so if I’m understanding you correctly than if I tell a function to print “These words”, when I call it it will print “These words” but then if I try to store “These words” as a variable, it won’t work because I never returned “These words” in the function. Right?

1 Like

Yes-you are correct.

there’s no special relation between return and variables

if you have a value you can assign a variable to it.

a function accepts input and produces output.

if you call a function, then you’ll get a value. (and if you have a value you can assign a variable to it)

printing writes data to stdout, that’s not an action that creates a value so you probably wouldn’t associate it with variables in any way, nor would you be able to use this lack of value to do further operations… for obvious reasons

print does return None, but if you wanted None you wouldn’t need print to obtain it

there are in general not a whole lot of relations between any two specific things. consider what they do individually and whether those things can be fit together in some way

1 Like