+ 1
Return
Hi, can someone please explain the use of "return" when we define a function in Python?
5 Respuestas
+ 6
Think of return as the value that the function produces or gives back (return) to the program.
def five():
return 5
just writing
five()
would not be useful, but
a = five()
would be the same as
a = 5
so now you can do something more with the return value of the function five()
+ 6
Negar Navidi ,
here is a simple code that demonstrates what `return` statement is doing:
def average_temp(temp1, temp2):
average = (temp1 + temp2) / 2
return average
temp1 = float(input())
temp2 = float(input())
result = average_temp(temp1, temp2)
print(result)
in this code, we take two float numbers as input from the user and store them in two variables (`temp1` and `temp2`). then we call the function `average_temp()` with these two inputs as arguments.
the function `average_temp()` takes two arguments. Inside the function, it calculates the average of the two values. after calculating, it sends (or "returns") the result back to where the function was called. finally we print the result.
(thanks to per bratthammar for this completion):
return always terminates a function and sends back the value specified after it; `None` if nothing is specified.
+ 2
return makes a function stop executing and returns a value, for example you have the function hello()
def hello():
return 'hello world'
every time you call that function, you get a value, in this case its the string 'hello world' (basically whats getting returned). you can now either assign it to a variable
x = hello()
print(x)
# Output:
# hello world
or find another use for it
x = hello().upper()
print(x)
# Output:
# HELLO WORLD
those are just two examples of what you can do (theres way more uses), just remember that the returned value is basically what the function equals to
+ 2
Thanks everyone ❤️🙏🏻