Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJay Reyes
Python Web Development Techdegree Student 15,937 PointsThe "or" statement and it's preference
self.value = value or random.randint(1, sides)
In the above does self.value assign to value iff the value is passed in with a nonzero?
Are we assuming that or
chooses the first object that changes -- so a changed object is more "true" than a default object?
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThe or
is evaluated in a “lazy” fashion. Each expression is evaluated in sequence. If a False
expression is found then the next expression is evaluated. If a True
expression is found (anything non-zero or a non-empty container), execution is stopped and the “True” value is returned.
In the case above, if value
is not passed in, (also if the value passed is actually zero), the parameter takes on the value zero which is considered false. This causes the random value to be generated and returned.
The statement is effectively saying “use the item value passed in if not zero, otherwise use a random value”
The Python and
is also “lazy”, stopping on the first False
value and returning it.
Post back if you need more help. Good luck!!!
Dave StSomeWhere
19,870 PointsDave StSomeWhere
19,870 PointsIf value is not passed (or passed as zero), then value is equal to zero which is
False
, so the random stuff is executed and assigned to self.value instead.