Cannot see result using return
Cannot see result using return
Why can I not see the result of jump()?
jump()
from random import randint
def jump():
return randint(1, 6)
jump()
Why do I have to use print instead of return to see the result?
print
return
What do you mean it doesn't work? It in fact returns a value. You can print it with
print(jump())– user2285236
Jul 2 at 17:49
print(jump())
because
print() prints and return returns as the names suggest– JacobIRR
Jul 2 at 17:49
print()
return
What is the "working" alternative here?
– Mad Physicist
Jul 2 at 17:50
Printing to stdout itself is pretty expensive and I'd prefer both a) not to see the garbage it throws into the terminal and b) not incur that overhead at all.
print is unnecessary when you want to just calculate the result of the function and use that value elsewhere, there's no need to see the value unless you explicitly call print()– roganjosh
Jul 2 at 18:00
print
print()
2 Answers
2
If you want any output from the code, then you need to use print, as return only returns the value to the caller.
print
return
print(jump())
In python shell, however, you can see the returning value of a function without printing.
>>> from random import randint
>>>
>>> def jump():
... return randint(1, 6)
...
>>> jump()
5
>>>
The confusion seems to be about the difference between a script and the python console, as you observed. This might be more helpful to others with the same misunderstanding if you said something like, "In normal use in a script" and perhaps gave an example of j = jump() and just use it, or print it also as a trace of the program.
– bitchaser
Jul 2 at 18:24
Your function returns a value, with nowhere to display it. Your options include:
from random import randint
def jump():
return randint(1, 6)
print(jump())
or
from random import randint
def jump():
return randint(1, 6)
test = jump()
print(test)
they have the additional option of printing within the method definition, i.e.
print randint(1,6) if printing to the console is the only desired behavior– R Balasubramanian
Jul 2 at 18:10
print randint(1,6)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Doesn't work how?
– Ilja Everilä
Jul 2 at 17:49