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 trial

Python Object-Oriented Python Dice Roller Project Breakdown

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 2 and 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.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 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!

Mindblown. :O :) Thanks again, Chris!