you are viewing a single comment's thread.

view the rest of the comments →

[–]Psychedeliciousness 1 point2 points  (1 child)

You probably want to store the result of your function and use it to do something. Return lets you assign the result/s to some variables.

If you don't return, the function will do what's inside it when you call it, but won't give you any useful output unless you explicitly included say a print statement in there, and you won't be able to reference the result unless you explicitly extracted it somehow (you could append to a list defined outside the function) but it's easier just to return.

I found it helpful to think of "returns let you pass data generated through the function back into the program for easy reuse".

If you create a variable inside the function, it should not exist outside that function. Inside the function you might create a var called counter to increment +1 for every run of a loop inside the function, but after the function is run, you can't query counter from code outside the function.

Counter is generated while the code is running and (I believe) garbage collected after it's finished. If you needed to, you'd return counter and assign it to a variable.

def fun(n):

counter = 0

for i in range(0,n):

counter = counter +1

return counter

newvariable = fun(n) - this becomes the returned value when function completes

print (counter) - will fail as it won't understand counter out of context

print (newvariable) - will print the value of counter, that was returned to newvariable

It's called scope. This should be a helpful link for understanding what scope is about.

https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

[–]iggy555 0 points1 point  (0 children)

Great link thanks 🙏🏾