Welcome to the Treehouse Community
Looking to learn something new?
Or statement execution
Part of the code for Kenneth's
__init__ method uses the
or statement in the following way:
def __init__(self, sides = 2, value = 0): if not sides >=2: raise ValueError('Must have at least 2 sides') if not isinstance(sides, int): raise ValueError('Sides must be a whole number') self.value = value or random.randint(1, sides)
I always thought the
or statement returns true if both sides of the statement is true.
How does the
or statement work here?
Let's say someone enters value of 2 so in that case, wouldn't both
random.randint(1,sides) be truthy, and the statement would just return
true? I'm not getting how this is equivalent to "return value if value != 0, or else, return random.randint(1, sides)," which is what I'm assuming the statement means.
Chris FreemanTreehouse Moderator 67,989 Points
In Python, the
or is not a purely logical evaluation (see docs).
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
If used as condition in an
if statement, then the truthiness of "2" would interpreted a "True".
Post back if you have more questions!