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 trialJustin Sana
3,501 PointsRPG Roller - Task 2
Having trouble with this one - mostly don't understand what the prompt wants me to do when I get to the append part. I looked through the community boards and it seems like there's different ways to answer this challenge.
I included # Comments of where I think I understand what is needed and comment where I think I get lost. Please help!
import random
class Die:
def __init__(self, sides=2):
if sides < 2:
raise ValueError("Can't have fewer than two sides")
self.sides = sides
self.value = random.randint(1, sides)
def __int__(self):
return self.value
def __add__(self, other):
return int(self) + other
def __radd__(self, other):
return self + other
class D20(Die):
def __init__(self):
super().__init__(sides=20)
from dice import D20 # import D20 from dice.py
class Hand(list):
@property
def total(self):
return sum(self)
@classmethod # Create classmethod named roll
def roll(cls, dice_numb):
dice_numb = [] # Create an empty list
for _ in range(): # this is where I think I get lost
dice_numb.append(D20)
return dice_numb
1 Answer
Ave Nurme
20,907 PointsHi Justin
I've seen quite a several and different approaches to solving this task but here is my solution which passed:
from dice import D20 # import the D20 class
class Hand(list):
@property
def total(self):
return sum(self)
@classmethod # create a classmethod named roll
def roll(cls, dice_numb): # take the number of dice as an argument
nums = [] # create an empty list
# in the next loop we append a D20 to our list equal to the
# number of dice given as an argument to the roll classmethod
for _ in range(dice_numb): # the loop runs as many times as what is the value of dice_numb
nums.append(D20()) # append a D20
return cls(nums) # return the list of D20s, classmethods need 'cls' here
For instance, if we called Hand.roll(2), the number '2' in the parentheses is the 'dice_numb' so in this particular case the loop runs 2 times.
I think quite many students have struggled with this challenge, incl myself when I learned this topic. I tested this solution and it passes.
Hope it helps!
Justin Sana
3,501 PointsJustin Sana
3,501 PointsThanks Ave!