+ 1
Returning Functions... NEED HELP
Hi, I would aprreciate so much if you could help me with the following code: >>> def short(x, y): if len(x)<len(y): return x else: return y short("Hello World!", "Bacon and Eggs") >>> I have no idea why it has no output. Plus I still haven't quite understand the return statement... Thank you for your time!
7 Answers
+ 3
Return statement in a function gives a value to the function that can be printed using the print statement, assigned to a variable, used in comparisons....etc
Calling a function means executing that block of code inside the function not returning its value
In your code you called the function and the code inside it was actually executed
One thing you can do is replace that return object with print(object), so that when the function is called the print function is executed
Another thing is to print the function just as maf did
Keep the return statement and try this:
a = short("Hello World!", "Bacon and Eggs")
print(a)
The output will be as expected
You see how the value of the function is assigned to the variable a?
You can check that topic in the Python course for better understanding
+ 5
This is a bit longer but can be understood easy:
result = short("Hello World!", "Bacon and Eggs")
How does it work: With short(...) you call the function. When function is doing "return" and gives a value back, this returned value is stored in variable result. No you can print result with print(result).
+ 3
You have to print what you return lol. Returning a value on itself doesn't output anything on the console.
+ 3
Thank you all so much for the explanations. I've now truly understood the return statement. My mistake was thinking it would also print...
+ 2
print(short("Hello World!","Bacon and Eggs"))
+ 1
Return statement means that there is nothing else in that function and it has ended, whatever u write after return inside function won't be reached
0
def print_numbers():
print(1)
print(2)
return
print(4)
print(6)