Reputation: 361
I was reading up on questions from a python quiz. Here is the following code and its respective question:
class Player(object):
def __init__(self, name, health):
self._name = name
self._health = health
def get_health(self):
"""Return the players health."""
## LINE ##
What is the required code for ## LINE ##
so that the method satisfies the comment?
(a) print(self.health)
(b) return self.health
(c) print(self._health)
(d) return self._health
(e) More than one of the above is correct.
So, I'm wondering, is this question ambiguous?
If I state that a specific function's purpose is to "return the value of x", could that not be interpreted as both literally employing the return
command to give x's value and using the print
command to display the value.
Both give the same answer at face value in the interpreter. Of course, things are different if you attempt to manipulate it indirectly:
get_health() * 5
yields a normal output if using return
get_health() * 5
yields an error if using print
So should I always treat 'return something' as actually using the return
command?
I suppose print
and return
would both be viable only if the function's purpose said something like "Display the value in the python interpreter".
Upvotes: 0
Views: 44
Reputation:
The correct answer is simply d): return self._health
.
You almost answered your own question. Return in programming parlance means use of (the) return
(Python/C/... statement, or an implicit return in other languages, etc).
The point here is that that the comment is meant for programmers, not users.
A print statement would imply something to the user running your program ("return output visible to the user"), but the user will not see or know about that comment.
And, as you already pointed out, the use of return
ing an actual value allows constructs like get_health() * 5
.
Going one small step further, I would expect a printing function to be called print_health()
; but that's up to the logic of the programming standard & style that is being used.
Upvotes: 1