One aspect of subroutines is driving me bonkers: the ‘return’ statement.
When I created a subroutine that determines some kind of result/output, then try to use the result/output outside that subroutine, I got errors.
I learned about the ‘return’ statement and tried that with no success.
Then I discovered the ‘global’ attribute, which is great and very effective.
I just completed Day 47, which features Dynamic 2D Dictionary work. I initially tried using a subroutine to create a 2D Dictionary of players , attributes, and values, but my resulting 2D Dictionary wasn’t ‘visible’ outside the subroutine.
So, I kinda cheated and assigned my 2D Dictionary a global variable.
I love global!
But this is not the first time I’ve pulled an end-around on the return statement by using global and I want to learn when, where, and how to use return.
Searches online yield lots of information, but I continue to have no success.
Can someone point me to or give a description of the purpose and use of the return statement as it applies to subroutines? I have a long history of “OH, now that see it put THAT way, I fully comprehend!”
Maybe a link to a repl that contains a subroutine with a return statement so I can see what a working one looks like and try to figure out what I’m having trouble with?
Thanks!
The return
statement, when encountered within a function or subroutine, immediately stops the execution of that function and returns control to the caller. It can also pass data (values, objects, etc.) back to the caller. This is useful when the function is meant to compute something and provide the result for usage, as demonstrated below:
def test_func(a, b):
result = a + b
return result
result = test_func(1, 9)
print(result) # Output: 10
return
statements can be used to avoid global variables. Since global variables make code harder to understand and debug, using return
to pass data between functions gives better organization and readability.
Sky,
Thanks for the quick response. I read it almost immediately, then went out to run errands while it percolates.
Everything you say and the code you posted all fits my understanding of how return works.
I must be doing something wrong. So I’m going to play around with what I intended to do, if I continue having trouble, I’ll post the actual code and see what it is I’m missing.
Thanks, again,
drats
Can I see your first attempt at this?
The global
keyword is bad practice.
You should be returning from functions whenever you can, instead of creating a variable which you edit inside of the function.
@dratsaBgumS How I learnt return
was by imagining that it allows your function to a variable. It brings back the data after the word return
back to the main program.
def display(text):
print(text) # This isn't a return statement; it's print()
# This displays None:
print(display('Hello, World!'))
The reason that the program displays None is because it’s essentially printing a print. It’s just a no-no. So you get a None.
But what about replacing print()
in the function with return
?
def display(text):
return text # This is a return statement. It gives `text` back after calling the function.
# This displays the text:
print(display('Hello, World!'))
data = display('hi')
print(data)
# This doesn't display anything:
display('Hello')
Now, you are storing the function as a variable, which gives back ‘hi’, storing ‘hi’ in the variable. It is then printed. Or, you print the function that returns ‘Hello, World!’. Either way, the function gives back the text, then you print it.
For the last line, nothing is displayed as you aren’t printing, only returning. Return is in the background, so nothing shows up.
Hope this helps!
What?
That’s an undefined error.
Oh wait messed up the variable and line the comment was on. Give me a sec.
Good to know this, I’ll try to avoid it in the future
All,
Thanks for the replies and info. Absent my original attempts to use the return statement, I don’t think I’ll ever know why I kept having trouble with it.
After reading the info you all provided I started with Sky’s little demo and it worked.
So, I went back to my Day 47 code, ripped out the global for the 2D Dictionary, and re-tried using the return statement. It worked!
So, I played around a bit and it looks like I now know how to use return.
I have to admit, I find it kind of funny that my ‘main’ program is simply three function calls and the rest is all subroutines.
Thank you all, again, for the assistance and info, it’s much appreciated!
drats
Well, you will if you send it… We’re happy to explain if you can just send it here.
A few thoughts:
1.) You don’t mention which language you’re using. As hard as you may find this to believe a “return” statement is not a universal concept. In functional languages for example, if there is a return statement the behavior is significantly different than it is in imperative languages. So, for future reference, don’t assume everyone knows which language you’re speaking of. Tell us. You’ll find that if you keep on with software development details are EXTREMELY important.
2.) There’s a concept that almost never gets mentioned but which is pretty fundamental to understanding how software works. The instruction pointer (IP) tells the central processing unit (CPU) what is the next instruction to execute. Now, due to the way memory is structured in a computer, subroutines are usually located in memory somewhere outside of the main body of the program. So when I call a subroutine from my code, under the hood the operating system must do a few things:
a.) Figure out where the subroutine I want to call is located.
b.) Stash my current location in temporary storage
c.) Either shove any parameters I want to pass on to a stack or pass their addresses to the subroutine
and a few other things–my point is that this is not a trivial thing.
When your subroutine is done executing, you need some way to inform the OS to “return” to the point where execution left off before the IP was pointed at your subroutine. This is why point (b) above is important. If the OS doesn’t stash the location where the IP was at before it ran the subroutine it has no way to know where to “return” to. It’s also possible that you may wish to hand back something that you calculated during your execution of the subroutine. This is often done via a return statement although it doesn’t have to be.
OP’s doing the 100 days of code course in Replit. There are a couple, but this category is only meant for the Python one.
Oh-ok. I didn’t infer that from the context. Thanks for the heads up.
Yeah… that’s the problem: once I decided to go with the global thing, I didn’t keep the failing return code.
Fortunately, I’m still playing around with return and today’s question will be accompanied by the actual code.
So, you’re still facing issues with return
?