Return statement?

how do i use the return statement?
i keep trying to research it, and i find plenty of websites that explain it-- but all they say is that it “returns the function to the caller”, but i don’t know what that means, or what that does.
can someone please try explaining what, exactly, the return statement does, without just saying it “returns the function to the caller”?

1 Like

Sorry could you give us the repl link?

The return statement sends the result back to the program. For example:

def one():
  return 1+1
number = one()
print(number)

The number 2 will be displayed. This is a very basic example.

1 Like

oh, there’s no specific repl. just trying to figure out how to use the return statement in general

1 Like

cool, thanks. that’s a bit more helpful : )

1 Like

oooh sorry ok so basically for return statements, a function’s purpose is to basically be able to run code without having to rewrite it, so if I wanted to like print “Hello World” two times I could:

def hello_world():
    print("Hello World!")

hello_world()
hello_world()

the return function basically allows you to make it give you back something if you call it:

def add_two_num(num1, num2):
    return num1 + num2

print(add_two_num(1, 2)) # 3
2 Likes

The cool thing is that you can use it to break a function as well since everything after a return is not executed.
As for the return value, be wary of what language you use … rules vary

3 Likes

This is Python so we already know the language.

1 Like

The return statement gives you a value output of a function. A normal function returns nothing at all.

def add(a, b):
    print(a + b)

output = add(5, 6)

# prints None
print(output)

But using return can give you results from a function.

def add(a, b):
    return a + b

output = add(5, 6)

# prints 11
print(output)

However calling return ends the funciton.

def add(a, b):
    return a + b
    # NEVER gets run
    print("hi")

print(add(12, 15))
2 Likes

i missed the tag sorry.
So main thing to watch out is assignment on return. If you return n values, you need n assignments (_ are ok also)

def f(...):
  ...
  return 1, 2, 3

a, b, _ = f(...)
1 Like

thanks everyone, you’re all being very helpful! i understand it much, much better now

3 Likes