Python Object-Oriented Python Dice Roller Project Breakdown

daniel steinberg
daniel steinberg
13,402 Points

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

please explain the purpose of this line of code.

as I understand it, self.value should be zero sometimes since its an "or", but after running many times I never get a zero:

import random

class Die:
    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)

[MOD: edited code block - srh]

daniel steinberg
daniel steinberg
13,402 Points

PS..sorry for being lazy and not looking at previous questions..I see this has already been answered

Steve Hunter
Steve Hunter
Treehouse Moderator 57,556 Points

Have you understood the answer to your question?

Steve.

daniel steinberg
daniel steinberg
13,402 Points

what if you actually wanted a value of zero to be valid and not false, for ex..if you roll a seven and want the value to be zero (not interpreted as false)

Chris Freeman
Chris Freeman
Treehouse Moderator 58,893 Points

One way to allow for the value to be 0 you could:

  • set default value to negative value value=-1
  • use if statement
if value < 0:
   self.value = random.randint(0, sides)
else:
   self.value = value