Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Dice Roller Project Breakdown

26,577 Points

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
Chris Freeman
Treehouse 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!

26,577 Points

Mindblown. :O :) Thanks again, Chris!