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

self.value = value or random.randint(1, sides)

For the def init Kenneth has:

def init(self, sides=2, value=0):

I'm confused on the code that reads:

self.value = value or random.randint(1, sides)

why is it value "OR" random.randint(1, sides) rather than just random.randint(1,sides)? Why does value's default value have to be set to 0 in the init method?

Thanks for the help in advance!

1 Answer

self.value = value or random.randint(1, sides)

This means if a value is passed in, assign it to self.value. If no value is passed in, use a random number between 1 and the number of sides.

You can check the function by creating some objects with value and without value and printing them out. (I'm guessing this code creates a Die?)

die = Die(value=3)
print(die.value) # 3, equal to the passed-in value
die2 = Die()
print(die2.value) # no value is passed in so it will be 1 or 2

In Python 0 is evaluated as False. When you assign a variable as something False or something True, it will be assigned the "truthy" value. You can try this in the interpreter:

>>> something = 0 or 5
>>> something
5

5 was assigned to something because 0 is falsy.