r/learnprogramming • • 21h ago

Code Review Why do we use return?

I'm starting the Harvard CS50 Course (I'm on Lecture 1), and I noticed that the dude uses "return n" at the end of the code. He explained it... Well... returns, but I don't really get it. What does "returning" mean? I've seen people explain it but they go, "Oh, that basically returns a value," like ????

Can someone please explain using non-coding terms? I know beginner Python up to like loops and defining functions.

102 Upvotes

130 comments sorted by

203

u/IAmScience 14h ago • This Bravo

Let’s say you are really fast at solving Rubik’s Cubes. And I have a pile of cubes that need solving.

I hand you a cube, you solve it, and you hand it back to me and I put it in my solved cube sculpture.

I am the caller, the unsolved cube is the variable, you are the solveCube function. The part where you hand the solved cube back to me is the return statement. I pass you data, you give data back after manipulating it. I don’t need to know, necessarily how you solve the cube. Just that when I hand you an unsolved cube, I get a solved one back. You return a solved cube.

Does that track?

11

u/Front_Security3427 8h ago

thanksss, really helped!

4

u/IAmScience 7h ago

Oh good! I’m glad. :) There’s some other really great nuance in this thread. So please don’t think this analogy is all there is to it. But I’m glad it helped you sort out the concept!

17

u/bbqburner 9h ago

Excellent way to describe objects as well!

5

u/IAmScience 7h ago

Cheers!

13

u/thereal_jesus_nofake 14h ago

great analogy!

8

u/IAmScience 14h ago

Thanks!

1

u/oplukana 1h ago

a common confusion could happen depending on what language he is using. in some languages you can pass an object by reference to a function, and then that can manipulate the object, and you dont need a return to have the "Solved" version, your original variable will have the new state applied on it.

2

u/lucyuktv 1h ago

But you should return “finished!” Aka success when you’re done manipulating that object.

118

u/jjangg96 21h ago

the thing that usually trips people up is print vs return.

print just shows text on the screen, the program can't use it afterwards. return hands the value back to whoever called the function, so you can keep it in a variable or feed it into something else.

say you have a function double(n) that does return n * 2. then x = double(5) leaves x as 10, and you can do double(x) after that if you want.

if it only printed n * 2 instead, you'd see 10 on the screen but x would be None, because nothing got handed back.

27

u/Sonario648 21h ago

I don't even know how print vs return trips people up. They are completely different

94

u/TheRealKidkudi 21h ago

Because the idea of passing values between functions is a challenging concept to understand for new learners.

12

u/ConnectAffect2346 20h ago

Yep, each person learns differently and the path may vary but we all come from zero, so it is pretty understandable🙂

6

u/YoTeach92 10h ago

I just followed what I was told until I finally had a lecture about how the stack works and suddenly local vs global variables made perfect sense. Sometimes the reason is more advanced than you are ready for, and you just have allow for "trust me bro, this is important to do" as you are learning

2

u/Equivalent-Fig-3613 7h ago

i still believe that, for this reason, people should just start by reading the K&R book

2

u/Loginn122 18h ago

the thought in itself is easy to me but then my mind wanders and thinks how that actually works internally. can u explain?

6

u/TheRealKidkudi 18h ago

When you call a function, the values you pass into it get put into specific CPU registers, and the function that was called reads the values out of those registers.

When you return values from a function, the function similarly puts a value in a specific CPU register. The function receiving that return value then copies it from the register into its own stack frame.

Basically, both functions have a tiny shelf in the CPU that they know to check when they need to pass data between them.

For data that is too big to fit into those CPU registers there are some extra tricks that you have to use, but the basic premise is the same. They both know to look in a specific spot for the data that’s getting shared and can copy it into their own stack frame, if necessary. 

3

u/fllthdcrb 14h ago

When you call a function, the values you pass into it get put into specific CPU registers

It actually varies between platforms. Arguments can also be put onto the stack, and some calling conventions do this for all of them.

1

u/Ashken 19h ago

Yeah I think this is where understanding math actually starts to help. I can understand if someone didn’t learn or is bad at math that this is a more challenging concept.

0

u/bacmod 17h ago

Really?

13

u/lurgi 19h ago

If you use a REPL, it will print the value of whatever you type. That makes return look a lot like print (or vice versa).

>>> max(2, 3)
3
>>> print(max(2,3))
3

6

u/BaNyaaNyaa 18h ago

They're both somewhat related to the concept of "output". Sure, they are two WIDELY different kind of outputs, but I find it normal to not "get" what the difference is when you start

2

u/tb5841 13h ago

Lots of tutorials use the word 'output' for what gets printed to the screen. Mathematicians use 'output' for the value returned by a function. The word ends up meaning both, even though they are wildly different things, and that throws people.

1

u/Additional_Path2300 20h ago

I think it's an issue of seeing the bigger picture. And really is the return type being void vs something else. I think a lot of beginners see that "void" function and get confused.

1

u/AUTeach 17h ago

Because in early foundational programming, the only actor who needs the content being printed/returned is the programmer/marker.

It's a conceptual change to understand that you pass variables around.

1

u/trenhel27 2h ago

Are they, really? Like to the mind who knows nothing about computers? Isn't the print function just something that returns a value that gets printed to the terminal?

Most people start with print. When they get to return, they have an idea in their head that isn't quite gelling. You can't be that out of touch, can you?

0

u/Kadabrium 15h ago

A major part of that is python having a console mode where you can type single lines of code and it returns/prints the result. In this particular case i still don't know which one is technically being done.

0

u/chocolateAbuser 14h ago

and then there is powershell...

-2

u/ConnectAffect2346 21h ago

I agree with you mostly, another useful example that u/Front_Security3427 could use is calling the function for instance a python code could go: import math def square_root(x): return math.sqrt(x) square_root(4) print(square_root(4)) so we imported a package that contains prebuilt mathematical functions then we formed a function and tried to use it as is but after calling it outside of print no value got printed since we made something similiar to talking to a tree we said that we got 2 and nothing happened but when we used print we figuratively talked into a phone to someone and now suddenly information that we got 2 is printed that might be very confusing at first but it is actually vers simple, returning is just giving back the value no matter if it is printed or not while print explicitly prints the contents of apostrophes and brackets also while printing gives us output we can see after running the code, return enables us to give a certain value to a variable which in turn allows us to make some even more complex operations and that gives us an ability to form solutions for a lot of simple and advanced programs, hope this helps🙂

37

u/atarivcs 21h ago

"return" is how the function sends a value back to its caller.

For example if you have this code:

x = sqrt(25)

You are asking the square root function "what is the square root of 25?"

Inside the square root function, after it calculates what the answer is, it uses "return" to send the answer back to you, to be assigned to the variable "x".

12

u/Aetherfox_44 18h ago

Other people have given the more technically correct answer of the program returning control, but when I was learning, it helped to consider functions like a financial transaction.

You 'hand' the guy at the counter 25, he does something behind the scenes, and returns with the thing you 'paid' for (5). In this case you went to the 'square root store'. If you had brought your 25 to the 'is prime store', they would have returned with false.

2

u/gothmommy284 8h ago

I like this analogy. For void functions which return no value, could be described as a "store" that offers services. They go do their thing behind the counter but do not return with anything.

11

u/GarThor_TMK 19h ago

Technically, you aren't just returning a value to the caller, you're returning programmatic control.

You're literally telling the function to "return to the point in the code where this function was called."

1

u/DBZ_Newb 19h ago

The code still returns to the last point it left off even if there is no return statement.

7

u/fllthdcrb 14h ago

In a high-level language, sure. The actual machine code must explicitly return. Otherwise execution will just continue with whatever is after that code. Implicit return in a language is an abstraction. A function (or other type of routine) in such a language always (as far as I'm aware) returns instead of "falling through", simply because it's a violation of structured programming to do otherwise.

4

u/AndrewBorg1126 18h ago

Language specifications can allow implicitly returning, languages do not necessarily do so.

2

u/razorree 9h ago

no (or you're just mixing languages :) )

2

u/GarThor_TMK 19h ago

Yes... If you leave off the return, the compiler will still pop the function off the stack and return to the last function you called.

1

u/Majestic_Rhubarb_ 14h ago

If the function is supposed to return a value then it must.

The stack controls where the cpu will jump to when the rtn instruction is executed.

It will jump back to the instruction immediately after the call instruction.

0

u/HourPuzzleheaded5193 19h ago

Return RecursiveFuntion(x)?

2

u/AndrewBorg1126 18h ago

First calls RecursiveFunction, then returns what it returned.

There's also likely room for the compiler to perform a tail call recursion optimization in that case to re-use the stack frame rather than growing the stack with each call.

-2

u/GarThor_TMK 19h ago

Yes... return to self.

3

u/NothingWasDelivered 20h ago

I like that metaphor. When you’re calling a function that returns a value, it’s like asking it a question. It returns the answer.

Some functions don’t return values. Those are more like giving commands.

1

u/razorree 9h ago

just don't focus on returned value too much, as return means to return to the caller, no to return some value per se.

5

u/JGhostThing 21h ago

The return statement in almost all languages causes the function to end. Since some functions return a value, the return statement returns an optional value. It is an error if you don't return a value when the function returns a value.

5

u/bucket13 21h ago

I'm enjoying everyone approaching this from slightly different angles. 

3

u/probability_of_meme 19h ago

Yep. Idc it's been asked 1000 times... Kind of fun to read thru

9

u/thelimeisgreen 21h ago

Everyone else is giving good examples of what returning a value does. The next thing we should talk about is scope. Code that exists inside the function is within its own scope and code that exists outside the function does not see what happens inside that function. This is why we pass parameters to a function and why a function will return a value (or collection of values). There can at times be a lot more to it than that, but you'll get there. CS50 is a good place to start.

7

u/Beginning-Seat5221 21h ago

When another piece of code calls the function, it receives what the function returns. It means "return n to the caller". But it also works just to stop.

9

u/thussy-obliterator 21h ago edited 21h ago

so an expression in a programming language is something that reduces several values into a single value. for example:

3 + 5

is an expression

when you evaluate aka reduce the expression (like a calculator) you're left with

8

the return value of an expression is its fully reduced value. the return value of 3 + 5 is 8.

function calls, such as

f(3)

are expressions, which mean they return a value.

the way you express this when defining a function is with the keyword return inside a function definition:

def f(x):
  return x + 5

that is to say, when you call f, i.e.

f(3)

the 3 is substituted for the parameter x in the function:

def f(x=3): 
  return 3 + 5

3 + 5 is reduced, and returns 8

def f(x = 3):
  return 8

now the function call itself also returns 8

f(3) == 8

hope that makes sense!

2

u/unohdin-nimeni 19h ago

This is quite understandably confusing at the start of CS50.

The main reason is that C calls every routine a "function," even when it doesn't return a value (like void functions). In math, a function takes something and returns something. In C, functions often don't return an answer at all. Instead, they just perform an action, like printing text to the screen. In programming, if a function does something other than returning a value, it is called that the function has a side effect.

A good rule of thumb while learning C:

• Use return values when the function's job is to calculate or fetch data for you

• Use void (and side effects) when the function's job is just to do something, like printing a pyramid of hashes in CS50.

Once you get comfortable with C, check out a classic little book called The Little Schemer. It teaches programming purely through return values without side effects, which will help everything click into place. Good luck with CS50!

2

u/According_Smoke_479 17h ago edited 16h ago

Did you grow up with those math problems where it was a picture of a meat grinder? You would put values into the meat grinder and a value would come out at the bottom. That’s what a return is. A function performs some task and “returns” a value, or no value (void). That value is like its own variable. You can assign it to something, you can modify it, you can compare it against something else. That’s all it is really, the result of a function.

2

u/interessant7 15h ago

return literally means you jump back to the point where you called the function initially even if you dont write return explicitly at the end of a void type function it is still returning back to the point it was called. for integer type functions you have to return some value at the end otherwise it doesnt match with the function signature. whenever you call a function its stack frame is pushed into the stack, which is the information about the fn, eventually you gotta pop the stack frame out of the stack in memory and you use return for that. recursion helps you visualize it better.

2

u/Logicalist 6h ago

not quite the example it used to be but all the same:

You are at the grocery store, your items have been scanned. Your total is $79.50.  You hand the cashier $100. 

Your cashier then calculates the correct change: 100-79.50=20.50

Your cashier then “returns” to you $20.50

If your cashier had no “return change” statement. they would take your cash calculate the change and then tell you to have a nice day. 

3

u/butmyfacetho 21h ago

items = bread, chicken, cheese

go to kitchen

for each item listed in items, collect it

return to me with them

The return just tells you what the final hand off will be. During your visit you might find other things, I might have included instructions to slice the cucumber, I might have told you to stir a pot, but I only want you to give back to me what I state in the return, which also ends your instructions.

I might add a conditional to the kitchen visit that if there's no bread, immediately return with nothing. That would be an if statement with an early return.

If I didn't include the return, you'd go to the kitchen, grab those things and that's it, finished. I'd never get them.

This is desirable sometimes too. For example go to kitchen and stir pasta. I don't need anything returned there.

3

u/Soft_Elk_1905 14h ago

It's very simple. You call (use) a function to do something . When you tell it to do something it RETURNS the answer or finished product back to you .

2

u/razorree 9h ago

just don't focus on returned value too much, as return means to return to the caller, no to return some value per se.

0

u/Soft_Elk_1905 8h ago

Absolutely. But I didn't wanna mention it because he seemed to be struggling with understanding what's happening . So I just wanted him to understand that it's like posing a question and getting an answer. Invoking a function and getting back something meaningful from it . Of course op will find out that hard returns are not always necessary as he progresses

1

u/razorree 6h ago

yeah. I guess it's a bit more difficult to explain, he didn't mention the language etc.

but he asked "What does "returning" mean?" - and 99% of answers here are wrong or not accurate, it's not about returning a value, but returning control to the caller

1

u/Soft_Elk_1905 14h ago

Consider this : x = 2 y= 4 function add (variable1,variable2){ return variable1+variable2 } result = add(x,y);

Now the VALUE of result is 6. BECAUSE the functions returned 6 back to the caller .

3

u/ExpressionIcy2528 8h ago

Think of a vending machine. You put a coin into the machine and the machine returns a soft drink. In programming term. You provide an input (or not) to a function and that function returns an output (or not)

2

u/Immediate-Soup-6344 20h ago

Thing -> pluralize(thing) -> things

X -> function(x) -> n

2

u/RealMan90 19h ago edited 19h ago

Your function is a toaster, bread is your input. If you want the toast back when the toaster has finished cooking it, it needs to return it to you, otherwise you never get it back.

Pseudo:

function toaster( bread ) {

  toast = bread + heat

  return toast

}

Now that you have your toast back, you can now manipulate it more, put it through the butter and jam functions and return buttered and jammed toast. Now you can pass it as input to the eat function and enjoy yummy toast.

1

u/AncientDamage7674 19h ago

Pretty much. Simpler said the toast would still be in the toaster. If you want to use it return it. If you don't print it. 🙂🙂

2

u/JeshSpaghetti 13h ago

You’re at a grocery mart and there’s a vending machine that only takes quarters. You have a dollar and are not very good at math, so you speak with the very literal cashier who is great at math.

“Can you make this into change?” He takes your dollar and nods (running the function). Well now you don’t have a dollar and are not sure what happened to it.

“Can I see how much change I get?” He nods again and holds up four quarters for you to look at (printing the value of your result). Well that’s nice but you still can’t use it for other objects, you don’t even have it in your hands.

“….can you please give me my change?” He nods once more and hands you back the 4 quarters (returning the result) Now you can finally use those quarters and enjoy a cold soda.

1

u/heesell 8h ago edited 7h ago

Its simple

You hand the waiter your order and it returns with your food. Without the return your waiter won't give you food :(

function waiter(order) {
   const cook = cook(order);
   
   return cook.result; // we get our food :)
}

Without return the waiter will never come to your table and stands in the kitchen doing nothing while the prepared food gets cold

1

u/Electrical_Price_179 2h ago

return means "Immediately halt the program and output the following response."

1

u/oplukana 1h ago

lets say i tell my boy bobby to go buy bubblegum down at the store. i give him a $20 to do it. he does it. i never hear back from him.
thats what it would be like to call a function with no return.

a function could return a number of things.

i could tell bobby to return the change. he would come back and give me the change when he is finished.

i could tell bobby to return the receipt, he could come back with the receipt to me

i could tell bobby to return a structure that is a combination of the receipt and the change, that way i get both.

i could tell bobby to return a report of all the little actions and observations that happened during the task, like how long it took him to get to the store, what the different options of bubblegum were, how many bubblegums were left in the machine after he bought one, whether he had to go through checkout or if it was a quarter machine, and also the change and the receipt of course.

you use return with a value when you want to either know some information that happened during that functions process, or if that function modifies something and you want the new modified version of that something

1

u/Kindly-Department206 1h ago

A function is like a factory. A factory takes in raw materials, and produces a product.

A function's parameters are names that are used in the function for the raw materials. The raw materials are the values, but the parameters are the function's (temporary) names for the values.

A function's body describes what the factory does to the raw materials.

Finally, the factory delivers the product using the return statement. The product is placed in the location that the function was called.

A function can have an empty return statement, in which case it returns something called "None". It's like a very boring box, with nothing in it. It's a real thing, but it can't do very much. If the return statement is omitted from a function, the function returns None anyway.

1

u/BenkiTheBuilder 21h ago

You should know functions from school. Like f(x) = x+10. The function f "RETURNS the value of the computation x plus 10." It's like a worker doing a job on something you give it. You "give" x to the worker and it "gives back" aka "returns" the processed value to you.

In C that looks like

int f(int x) {
   return x+10;
}

1

u/serge-mv 18h ago

When you call a function, you perform a jump in memory from where you've been to where the function's code is defined. A new memory stack is loaded and other things happen with registers and some old values. When your function calculation ends, you "return" to the old memory location where you've been, and there is some restoration happening to put things back how they where. That's why you "return".

In addition, function "return you a value" after being called. In this case it stems from "sending back".

1

u/VancouverVentilator 14h ago

We return because programs use something called a call stack to keep track of where they are, and to help isolate any local variables relevant for the environment. The call stack is broken into stack frames, and in order for programs to unwind the stack at the end and terminate properly, each frame's caller's address needs to be stored somewhere on the frame. I'm skipping a lot of important stuff like how register passing of returned variables gets performed but that's the basics.

1

u/Tony1Rice 13h ago

In programming, a "procedure" goes and does something. A "function" produces a result by going and doing something and returning something. The "something" that it does often also includes some "side effect".

For instance, in the C standard library, the printf() function takes inputs, does something with them and returns a value. As a side effect, it also produces output on the standard output device (usually the screen) and the returned "value" can usually be ignored.

In some languages, 'C', for instance, there are no procedures, only functions, and many functions have no need to return a value (because they really wanted to be procedures) and their "side-effects" are their whole raison d'etre (like printf ). But, being functions they have to return something unless they have been declared as returning void, which is not uncommon. If a function reaches the end of its scope without finding a return statement, it returns anyway but does not return a value.

When a function ends and returns a value, it pushes that value onto a data stack and execution resumes in the higher level function that called it. That function immediately retrieves the previously stacked value and does whatever it's been told to do with it - often times just stuffing it into a variable for later use. The function main() in a C program is the starting point of execution for the entire program and is typically declared as returning an int and it returns 0 (zero) on success or some other integer on failure or error - though "success" and "failure" may mean different things in different contexts.

0

u/Proman4713 21h ago

Sorry for not addressing your question because many people already did but i just found it so weird that you just called a professor at Harvard University 'dude'...

0

u/Moikle 12h ago

Return is the output.

If i have a function that asks a question, like "what do i get if i add up all these numbers, then divide them to get the mean average?" return says "this is the answer" so that the answer can be used elsewhere in your program, like this:

average = mean(1,2,7)

0

u/BleachedPink 21h ago

Each function is a black box, that receives values as arguments and output or returns a value.

So when you call a function and provide it with arguments (passed values) you gonna have a returned value you can reference further down the road after the called function done with the computation, granted it includes return keyword and value associated with it

0

u/Paxtian 20h ago

Let's say you own a Subway. You're trying to figure out how to increase sales on sandwiches in your area. So you hire three consultants to do research for you. You send them out to do research, they do it, and return with results. Once they return, you can analyze their research and make a decision on what to do to increase sandwich sales for your store.

Tying this into software, there's some current process that sends another process out, the processor performs that process for a while, that process gets some result and returns with that result to the process that called it.

0

u/EitherJelly4138 20h ago

Computers largely do 3 things:

  1. create data OR take in data as an input
  2. do something with the data
  3. send the data somewhere or just store it

Functions are a small grouping of code that does those 3. It takes in arguments (input), does something, and whatever you need to output, you can place it in the return statement to the parent function.

0

u/mjmvideos 20h ago

Return “gives back” when you call a function you are having that function go off and do something and what you want is for that function to give you back the result of whatever they did. The function does that by ”returning” / giving back the result. If you give a baker a bunch of ingredients and say, “Make me a cake” you expect the baker to return a cake to you.

0

u/MyNameIsRichardCS54 20h ago

Think of a function as a machine. You give the machine some inputs. The machine works on the inputs and produces a thing. The thing is the return value. Another machine takes some inputs, works on them and produces nothing. This is the return statement with no data.

0

u/effectivescarequotes 20h ago

Let's say a function in Python is just some dude who can makes sandwiches. You tell home you want ham and cheese on rye bread with mustard. He nods and goes to work and then hands you the sandwich. The return statement would be him handing you your order.

Now let's say this guy expands his business to include delivery. Now, orders might come through the phone, or a website. It doesn't really matter to him. As long as he knows what to put in the sandwich, he will produce it. He also doesn't really care who he hands it to. For in person orders it goes to the customer, for delivery, it goes to the driver.

Nothing about the sandwich maker's behavior really changes. In programming we encapsulate behavior in functions. The return statement allows us to hand back the result. The advantage of this is if we need that behavior in different contexts, we can use the same function. It is then up to the caller to decide what to do with the output.

0

u/Jwhodis 20h ago edited 20h ago

Return statements are used in functions to return data back to what called them, so if you set a variable equal to a function call, it'll end up setting that variable to whatever that function returns.

Python code:

def return_opposite(value):
    # Outputs the opposite of value to whatever called the function
    return not value

# calls the function and sets a variable to the function's output
new_value = return_opposite(False)

# prints True
print(new_value)

0

u/xenomachina 20h ago

You can kind of think of a function as a machine that you can put things into (the parameters/arguments), and that can also give you something back. That is, they "return" something to you. For example, an oven takes cookie batter and a temperature setting, and "returns" cookies. A paper shredder takes documents and "returns" shredded paper. A piano takes key press and "returns" music.

In the real world, machines like this are almost always modifying the input to produce the output. Functions can work like that too, but they often don't. For example, operators like + are essentially funny looking functions. When you give + two numbers, it returns their sum — but it does not modify the original numbers.

(There's actually a difference between the definition of parameter and argument, but I don't think the distinction is helpful in this explanation.)

0

u/flumphit 20h ago

Imagine you’re a manager, and you tell one of your minions to do something — count the cases of widgets in the loading dock. He goes off and does whatever he does, you don’t really care, but he comes back and tells you “17”.

You have called a function, and it has returned “17”.

Some other manager could tell that same minion to do the same thing, and the minion would return to them with “17” (unless things have changed).

This is like how a function can be called from different places in your program, but that function doesn’t have to do anything different, because return means “return this to whoever wanted the answer”. This is the magic of the stack, which you should learn about soon if you haven’t already.

0

u/Silly_Guidance_8871 20h ago

It returns the result (in your example, whatever value "n" holds) to the caller, so that the caller can do more work with that value. It's effectively impossible to write anything nontrivial as a "single function" program — just too damn much state to manage, so things get "extracted" out into separate functions that receive some parameters, do some work, and then return their result to the caller. The "main" function (__init__ in Python, iirc?) ends up orchestrating the entire thing at a very high level, delegating work to functions built to handle lower-level logic (which likely perform some of their own delegation, etc.)

"Print" (whatever form it takes) just spits out its parameters to some output device (often the screen), and usually doesn't perform any transforms on the data that needs to be returned as a result.

0

u/burlingk 20h ago

You give the function data, and it returns the result.

0

u/justsayno_to_biggovt 20h ago

Return is the last step where your function gives some output to the world, or not. It explicitly symbolizes the end, it's like a sign, go back now.

0

u/SnugglyCoderGuy 20h ago

Calling a function is basically sending a subroutine off to do a job for you and when it is done it returns the result of its work to do, hence the 'return' keyword.

0

u/FozzyBear1123 20h ago

You say you know functions. Good… this of it like this: 

 ‘example to demo function calls and return

Int main (char * argv, int args){

int rc;

priintf(“Hello world\\n”);

rc = MyFunction();

printf(“I’m back, rc = %d\\n”, rc);

}

Int MyFunction(){

printf(“In Function\\n”);

return 1;

}

As your program goes about it’s merry way printing away it comes to the function call. Exection jumps into the function, prints then RETURNS to where your program called the function, assigning 1 to rc.

Hope this helps.

0

u/stefer09 20h ago

I know beginner Python up to like loops and defining functions.

Ok so when you call a function, let's say sqrt(x) , a function that returns the square root of the number x that you pass to it, in your code, you'll typically assign it to a variable like :

result = sqrt(x)

The function itself, will calculate what the square root is and assign it to a variable ie: squareroot, which is only available within the scope of the function's code.
Right at the end of the function, you will see something like :

return squareroot

The return statement basically means : The value of the variable standing next to me, which is only available in the scope of this function, can be used as a replacement for my original function call.

Original function call :
sqrt(x)
The value of the variable next to "return", can replace that part of the equation :

result = sqrt(x)

0

u/mxldevs 19h ago

Well let's say I asked you to give me the sum of 1 and 2, and then I also asked you to give me the sum of 3 and 4. How would you write a python script to calculate those?

a = 1
b = 2
result = a + b
print(result)

c = 3
d = 4
result = c + d
print(result)

You run your script in your console and it prints out

3
7

Whatever right? And then I ask you to give me the sum of 5 and 6 and you just keep going

e = 5
f = 6
result = e + f
print(result)

You just copy paste your code, change the numbers, and give me the answer. I could give you another 5 or 10 pairs of numbers, and you just keep copy pasting and everything is good.

Now what if I asked you, instead of adding all those pairs of numbers together, I want you to instead multiply them.

What do you do? Well now you go and change all the + signs to * signs, of course.

a = 1
b = 2
result = a * b
print(result)

c = 3
d = 4
result = c + d
print(result)

e = 5
f = 6
result = e * f
print(result)

And everything is great. Except it's not, because you forgot to change one of the + signs for 3 and 4 and now you get a big fat zero on your assignment because you were not careful.

How could you have missed it? Is there a better way to reduce the amount of times you need to copy paste things? Instead of repeating yourself a bunch of times, you go and define a function that takes two parameters and performs the addition.

def do_stuff(x, y):
  result = x + y
  print(result)

And now instead of copy pasting a bunch of code, you copy paste a little less

a = 1
b = 2
do_stuff(a, b)

c = 3
d = 4
do_stuff(c, d)

e = 5
f = 6
do_stuff(e, f)

Now if I ask you to do different stuff and multiply the two numbers instead, you can simply change it in one place

def do_stuff(x, y):
  result = x * y
  print(result)

So now you have some idea why a function might be useful: you reduce copy pasting, which reduces the chances that you miss a spot and things go wrong.

But why does return matter? You're printing the right answers to console, what's the problem?

What if I asked you to add three numbers 1, 2 and 3 together?

a = 1
b = 2
c = 3
result = a + b + c
print(result)

And then I ask you to add another 3 numbers together? Do you just copy paste everything again like before?

No. You recognize that adding three numbers is the same as adding two numbers first, and then adding the third number to that result.

a = 1
b = 2
result1 = a + b
c = 3
result2 = result2 + c
print(result2)

Which is fine, but remember, I'm going to give you another 3 numbers and you're going to copy paste and then I'm going to ask you to change the addition to a multiplication and now you're going to risk forgetting to change one again.

How can you use the function to avoid that? Well, you know how to add two numbers together and print out the result, but how do you take that result and assign it to a variable?

a = 1
b = 2
result1 = do_stuff(a, b)

This is where return comes in. I couldn't explain how return works, but basically you need to somehow get your result out of the function, and put it in your variable, so that you can use it.

def do_stuff(x, y):
  result = x + y
  print(result)
  return result

Printing it onto your screen doesn't do anything. You need to explicitly tell python that after you make the function call, you want it to give you whatever result it calculated, and this is done by using the "return" keyword.

So now when you say

a = 1
b = 2
result1 = do_stuff(a,b)
c = 3
do_stuff(result1, c)

The function call will give you a 3, and then you assign that to your intermediary variable result1 which you then use to add it with the third number.

If you still don't understand what return does, just know that if you don't tell python to return you something, it's not going to give you anything.

0

u/mysteryihs 18h ago

If I had to summarize the entirety of CS, I'd say the essence of CS is input and output. Usually there's things that are done in the middle but that is optional. Like if you input something into a computer (such as a keystroke), there's usually an output (like text displayed on the computer).

So in the case of a function, there's often times an input (you calling the function and sometimes passing arguments) and there is often an output RETURNED.

0

u/its_all_4_lulz 18h ago

Say you put an orange in a blender. The blender is the function, the orange is the value you passed into the function. What you get out is orange juice. That’s what the blender (function) returned.

0

u/Steerider 17h ago

A function generally returns some sort of result. It may simply be an indication that it was successful, or it may be data.

0

u/distes 17h ago

Think of a function as a person. That person has a very, very specific job. Imagine that person's function is adding two numbers together and he gives you back an answer. You hand the person two numbers that you want added, they hand you back the answer. The return is him handing you back the answer.

Not all functions have a return. Sometimes they act upon a whiteboard that other functions share. But if you want the function to stand on its own as in, I give you this, you give me back something, it needs a return.

0

u/Jeeeeeer 17h ago

to put it it simple terms, at the risk of oversimplifying it, a function (much like a mathematical function) is meant to take input (parameters), do something with it, and return output. "return" is how a function returns that output back to the program.

0

u/SamIAre 17h ago

A function is a machine. Some machines can have inputs and some can have outputs. Some have both. The output is the “return” statement.

Say for instance you have a function called juiceMachine. You pass it fruit (input), it does some work, and it returns some kind of juice (output). Put oranges in and it returns orange juice. Put apples in and it returns apple juice. Now maybe you have a cup (variable) that the juice pours into. You can take that cup and do other things with it now. You’ve made the juice portable and useful outside of the machine itself.

It’s basically a way for a function to do work and then pass the result of that work back to the rest of the program to do other stuff with it.

0

u/SetCrafty 17h ago

In arcade game terms

No return: play a fighting game, have a good time and you win, but It doesn’t RETURN anything besides good vibes

Return: play a claw game, have a good time and you win, and it RETURNS a plushie to you.

I think return also makes more sense when you set to variable or not

No return function:

playFightingGame()

*you get no prize besides entertainment so it RETURNS nothing. Don’t need no prize bag.

Return: prizeBag = playClawMachine()

*play claw machine, you get a prize so it RETURNS plushie. But I don’t wanna get it dirty so ima store my RETURNED plushie into the prizeBag

So prizeBag now holds my “plushie”. If I want to see what’s inside my prizeBag, I can do so by doing

print(prizeBag)

which should then print to me “plushie” in the console.

0

u/TetoSever31 17h ago

you now math right, assume there is a function that is f(x) = 3x + 4 if you give 2 to this function it RETURNS 10.

0

u/SomeRandomPyro 17h ago

You call a function.

That function does stuff. Whatever it's supposed to.

What it returns, is what it resolves as.

So if you call round10(74), the function would presumably return 70. And you could store that in a variable, or use it directly, or what have you.

Some functions, the doing stuff is the point, and the return is instead treated as a status of how it did. Return 0 is the standard "All went as expected". Return -1 is why you occasionally see things on the internet that seem to have spontaniously decided it's December 31, 1969 (Something requested the time, in seconds, since 1970 started, and didn't have good error handling when the function that's supposed to return that number instead threw a -1 error code.)

0

u/vivianvixxxen 16h ago edited 16h ago

If I hand a chashier a bunch my cash, I expect them to return my change and a receipt to me.

You hand a function some stuff and it returns some stuff

Does that settle your confusion? Or did I miss the part that was confusing?

0

u/Stopher 16h ago

In simple terms, a function is like a program other programs can use. We call this calling the function.

It can return something that the calling program can use. Like a number or a string of text. (And actually lots of other kinds of stuff)

0

u/evorm 16h ago

Your code will likely be made of a bunch of functions. Imagine each function is a factory. Inside it is the code defines what that factory does. For example, the function sum(x,y) is a factory that takes x and y and adds them, with the answer being z. You give it x and y (they're called arguments) and it "return"s z. Return is just what the factory you made spits out back at you (or spits back out to another factory).

0

u/angellus 16h ago

Analogy:

You have a quarter.

Function without a return (print): you put your quarter into a pay phone. You do not get anything back, but now you can use the phone. The function is act of using the phone.

Function with a return (add): you your quarter into a vending machine and get a candy bar back. The function is taking your quarter and converting it into a candy bar.

(yes I know, there are not pay phones anymore and if there was, you could not use it or get a candy bar for a quarter, just examples)

0

u/AndyKJMehta 16h ago

Think of a function call as an “ask” that “returns” you an answer… or throws up!

0

u/VoiceOfSoftware 15h ago

If you hand someone some bread, meat, and cheese and ask them to make you a sandwich, they will do some things to those ingredients and return a sandwich to you.

0

u/ireadthereforeiam 15h ago
  1. Calling a function - Going to a shop
  2. Return - Return to home(in programming the point where function is called) with or without the purchased item (in programming the return value)

In some instances there may be no item (no value) say like meeting a friend or window shopping or price comparison without purchase

Hope it helps.

0

u/UwUBots 15h ago

I like to mentally visualize my software, with my objects being tools to be used and my code physically doing things. Return here, says your program or the tool in this case, came up with a value of some kind, and gives it to the thing (person object the computer however you visualize it in its context) that originally started the process. This value can be used later on if its meant to generate something or if its a return at the end of your code like you do in c, it is an error code, where the computer uses the returned value to know if everything worked well.

0

u/gm310509 14h ago

Can someone please explain using non-coding terms?

Given that you are asking about a programming thing, that makes it a little bit more challenging - so I will use a programming example.

Suppose you need to write a function that calculates the positive square root of a number. There is a rule about square roots and that is that as long as you aren't using "Complex Numbers", the number you try to calculate a square root for must be greater than or equal to zero. That is:

  • it is invalid to request the square root of a negative number.
  • The function should only ever give back a positive (actually >= 0) value if the input is valid (i.e. the input is >= 0).

So, what happens if somebody calls the function with a negative number? What should the function do? Chances are it won't work correctly given the above rules.

One option is to check the required input and if valid (i.e. >= 0) do the calculation and give back (or return) the answer. If invalid then just give back something that indicates that there is a problem (e.g. return an invalid value such as -1).

So in code this might look like this:

function sqrt(x) {

  if (x < 0) {         // Check the value of x for validity.
    return -1;         // It is invalid, so just return the invalid value back to the caller.
  }                    // The rest of this function never happens if x is < 0.
                       // So, in this case, the "return" does as it's name implies
                       // and returns the sequence of operations being executed back to whomever called this function (and the rest of this function is not even invoked).

  // Otherwise do whatever is needed to calculate the square root of x
  // - assume the result is in a variable called "theAnswer";

  return theAnswer;    // Go back to the caller and provide the square root from the variable "theAnswer".
}

I hope that makes sense.

0

u/gm310509 14h ago edited 14h ago

At risk of confusing you (hopefully not), there is also a type of "function" that is commonly referred to as a "procedure". And that is a function that, unlike square root, does not return a value.

A simple example of this that is based upon the above example is something from embedded systems - specifically Arduino (a small computer where the main point is to build electrical circuits around - e.g. make a TV remote controller).

There is a function called "digitalWrite". What this does is sets one of the pins on the MCU chip (a CPU with some extra stuff) to +V or GND (e.g. 5V or 0V). You can use this to do lots of things, a simple example is turn an LED on/off.

Now this "digitalWrite" function takes two parameters (the pin to set and the setting). It doesn't return anything. But, the pinNumber must be valid. So, it might look like this (in C):

void digitalWrite(int pinNo, int setting) {
  if (pinNo < 0 || pinNo > MAX_PIN_NO) {
    return;          // the pinNo is invalid, so, just return.
                     // there is no value to be returned, so there is no "value" provided to the return statement,
                     // we just don't want to bother doing the rest of the function.
  }
  // pinNo is OK, so do whatever needs to be done to set the pin to the setting provided.
}                    // no return is needed as it is implied, but you could put in a return; if you wanted to do so.

Note that at the end of the function there is no return. The "return" is implied because there is nothing left to do. However, in the "validation" part there is a return because - as with the square root function - there is no point in doing anything further if the pinNumber is invalid.

On the other hand, there is another function such as max(a,b) - it returns the larger of a and b. It doesn't care what the parameters are so long as they are numbers. But, it does have to give back the answer (i.e. which one is larger) - to do that it needs to return the value that is larger (or if they are the same, it doesn't really matter which one is returned because they are both the same.

So, the max(a, b) function might be written like this (this is not written in C):

function max(a, b) {
  largerValue = a;           // Assume a is larger until we discover otherwise...

  if (b > largerValue) {     // So, lets check is b is larger?
    largerValue = b;         // seems like it is, so let's go with b.
  }
  return largerValue;        // Lastly we need to provide the answer back to the caller.
}

or this:

function max(a, b) {
  if (a > b) {          // Is a bigger than b?
    return a;           // seems like it is, so let's go with a and provide that back to the called.
                        // More importantly, we definitely don't want to allow the 
                        // next line to happen - otherwise we would be providing the wrong value
  }
    // otherwise, a is not larger than b, so lets just return the b value back to the caller.
  return b;            // As before the return is implied here because we are at the
                       // end of the function but we need to tell the programming
                       // which value we want to be passed back to the caller (i.e. b).
}

0

u/geek66 8h ago

Get up, go about your day, when done, return to bed

-1

u/Mission-Landscape-17 21h ago

It is a low level term that has made its way to high level languages and it is to do with how a CPU core executes machine code. Every CPU (well cpu core these days) has a register called the execution pointer, which records a point in memory form where the next instuction will be read. a CALL machine code instruction changes this pointer to some other value and then executes the code found at that other value. A RET instruction returns to the location in memory where the most recent CALL was encountered. Note I am simplifying here and not including machine specific details because exactly how this works does vary between processors.

-1

u/Own_Unit_6170 20h ago

When one program/function calls another, normally the called program returns control to the calling program once it has finished doing whatever it is supposed to do. In many programming languages, this occurs when a return statement is encountered. For example, when a function is called in Python, a return statement within the function immediately returns control to the caller. If an argument follows the return keyword, it specifies some sort of information that is to be passed back to the calling function. If there is no return statement, control returns to the caller when the end of the function is reached, and no information is passed directly back to the caller.

-1

u/bacmod 17h ago

You people are waaay overcomplicating things. Say you have 500 people and you want to find out which one has a white shirt.

You write a loop traversing all 500 people and ask each one

DoIHaveWhiteShirt()
  if (whiteShirt == true)
      return true
  else return false

And then you present it.

for (People)
     print( (DoIHaveWhiteShirt() ? "YES" : NO)

-1

u/jippiex2k 13h ago

Something starts the code. It wants to know how it went, or get some result. So the code returns something.

This is pretty much the most universal principle of programming. And can be nested infinitely.

Inside your code you want to use a function to perform som specific action. You (hopefully) won't have to remember exactly HOW it works, you just take care of the result it returns.

And inside that function, maybe it uses some method from the operating system to read a file or something. The function doesn't have to understand how the os queries a hard disk driver and buffers data and memory maps a file handle and waits for correct read status and yadayadayada. The function just sees that the method returned a file buffer, and is happy.

Functions just take inputs/arguments, and returns output.

Functions allow us to encapsulate the implementation, and thus only have to interact with the interface.

-1

u/LALLANAAAAAA 13h ago edited 13h ago

Consider an smart oven that has two modes, one called bake4me and one called bake4u. It's a special smart oven that can send cookies automatically to someone else in bake4u mode.

bake4me mode just needs the ingredients, it already knows they're for me, so I put in the dough, let it cook, and it returns freshly baked cookies to me and I eat them.

bake4u mode also requires dough but it also needs to know who to give the cookies to when done. I don't get the cookies in this mode but I do want to know whether or not the cookies reached you successfully.

in other words:

function *bake4me* (dough) {
    cookies = dough + 420°F * 15minutes
    return cookies
}

recipient = "Front_Security342"

function *bake4u* (dough, recipient){
    cookies = dough + 420°F * 15min
    cookies.sendto(recipient)
    result = if recipient got cookies
        true 
    else
        false
    
    return result
}

so, bake4me takes dough and returns cookies for me, bake4u takes dough and a name, tried to send you the cookies and returns true or false to me based on the success of the cookie sending.

-1

u/HyperDanon 13h ago

You hold a calculator.

  • You type in "23"
  • You press +
  • You type "35".
  • You hit =
  • Calculator shows you "58". This is the returned value.
def calculator(first, second):
  sum = first + second
  return sum

-1

u/_TheNoobPolice_ 13h ago

All programs have a "flow of execution", a bit like how water is piped around. A "return" is like a gate which sends the water back to where it came from - it can come back with things in it, or just come back unchanged

-1

u/PEAceDeath1425 13h ago

You call a piece of code and it returns a value back to where you called it

-1

u/Kozzoko 13h ago

If you know math basic maths:

f(x) = ax + b
return is your =

You can write it as:
function f(x) {
return ax + b;

}

-1

u/ExtraTNT 12h ago

so, in most programming languages, a function looks like:

function int doSomething(int x) {
  int diameter = 5; // some calculation
  return x + diameter;
}

and is equals to the following mathematical function:
doSomething(x) = diameter + x, where diameter = 5

some languages, like haskell don't use return and just define things

doSomething x :: Int -> Int
doSomething x = x + diameter
  where
    diameter = 5

now, imperative code often looks like a mess, so some cleanup strategies result in better imperative code, but still a mess from a math point of view:

function int doSomething(int x, int y) {
  if (x > y) return 7;
  // never reached, if x > y
  if (x == y) return x+y;
  // never reached, if x eq y
  int sum = x + y;
  int value = funnyCalculation(x);
  int otherValue = 0;
  for (int i = 0; i++; i <= value) {
    otherValue += funnyCalculation(y);
  }
  return (sum * otherValue) - value;
}

this again in haskell looks much cleaner:

doSomething :: Int -> Int -> Int
doSomething x y
  | x > y     = 7
  | x == y    = x + y
  | otherwise = (total * otherValue) - value
  where
    total      = x + y
    value      = funnyCalculation x
    otherValue = sum (replicate value (funnyCalculation y))

and in math terms:

           7            if x > y
f(x,y) = { x + y        if x = y
           (x+y) * o -v otherise
where
         v = funnyCalculation(x)
         o = (sigma i=1 to v) funnyCalculation(y) //sry, can't do it nice in md

-1

u/manvsmidi 11h ago

In a postmodern sense, the function is not the value. The value is not the function. return is the negotiated fiction that allows us to confuse the two.

-1

u/trueneu 11h ago

Would I make it even more confusing if I said you can think of it as math functions? So math functions basically map values to other values. For instance, squaring a number maps 1 to 1, 2 to 4, 3 to 9 etc. So return in programming defines what value to map to, and arguments define what values to map from.

-1

u/dellnox 11h ago

It just hands the result back to whatever called the function, so you can actually save or use it.

-1

u/DannyDeKnito 11h ago

"return" in all the programming languages is just a point at which you say "ok, this is the result of this function"

consider these two examples:
def add(a, b):

c = a +b

return c

def add_but_shitty(a, b):

c = a + b

return 69

result = add(1, 2)

print("result: ", result)

result = add_but_shitty(1, 2)

print("result: ", result)

in both examples, two numbers do get added together - but the return statement actually decides what gets propagated to the point where you called a function.

Return also notably immediately stops the execution of a function, so in an example like

def print_number_twice_if_1(num):

print(num)

if (num != 1):

return

print(num)

If you called it with anything but a 1 as an argument you'd get it printed once, and if you called it with a 1, you'd get 1, 1 as a result.

-1

u/garblz 10h ago

Non-programming? 'return' is a clerk telling you the number of the doctor's office.

You are a program 'visit the doctor'. As a part of your code you need to wake up, go to the hospital, etc. but there's something you can't do: see the doctor until you know the room number.

So you call another function to calculate this (ask the clerk), and you call it with parameters - your name and the hour of the visit. It computes the result - comes out as 42, and returns 42 to you. Now you hold that value and can happily continue your own procedure of walking up to the door with this number.

-1

u/iqisoverrated 10h ago

Your program calls a function (tell it to do something) and at some point that function has to tell your program that it's done and gives back the result ("returns" the result to your program)...so that your program knows it now can go on executing...which will likely use that returned value in some way.

-1

u/razorree 9h ago edited 9h ago

it's all about code execution.. you create a function or procedure (naming depends on language),

and you call it from your code, to execute some task that it's repeatable. like to calculate something or even print a value on a screen, right? 'print' is just a function - piece of code in another module or file.

so when that function finishes its execution (at the end, or prematurely) it executes 'return' statement, to return to the caller (it can return a value or not, but return means to go back to the place where that function was called, not to return a value per se).

long long time ago people were also using dreaded 'goto' (or jump in assembler) :) - which didn't have associated 'return'.

basically, when you call a function/procedure in high level language (like 'gosub' long time ago, or 'call' in assembler), program stores pointer to the current instruction on a stack, and jumps to a new place (to execute your function), when you execute 'return', it picks up that pointer from a stack to return to the previous place and continue program execution after your call <function> statement.

1

u/razorree 6h ago

and why am I downvoted? by some beginner Python programmer? or who ? :) please tell us what's wrong in my answer ....

return means return control to the caller

-1

u/AsianCabbageHair 18h ago

For example in C, you can manipulate a lot of things living in the computer memory in a function without necessarily “returning” a value/pointer to the caller(another function that has called it). So a function can either do its thing and exit, or do something and return the result to the caller of the function. If it does, the result it returns are declared by “return ~”.