Is my Python die class okay even though it differs from the solution?

November 13, 2026 4 answers
Asked by unlisted-parachute

My Die class rolls ten times and prints a list of results. The solutions manual instead has roll_die return one random number, then calls it ten times outside the class.

My version produces the output I wanted. Is there a reason to prefer the manual's approach?

Answers

m5~checkout_641

Your approach is fine for a program whose only job is to print ten rolls. The difference is that the manual gives the caller more control. A method that returns one roll can be called twice, ten times, or as many times as needed.

Printing and returning are different things. Your method displays the list but does not return it, so a caller can't use those results in a calculation. In Python, a function with no explicit return gives back None.

unlisted-parachute:

So if I wanted to add up the rolls, returning the values would let the rest of the program use them?

x203!idx_58:

Exactly. You can collect the returned numbers in a list and use sum on it, or add each result as you roll.

Reply to this answer
u1.stapleFree

Think about what belongs to the die versus what belongs to the program using it. The die needs to know its number of sides and how to produce a roll. The calling code can decide how many rolls it wants and how to display them.

That separation makes it easier to reuse the same class when the output changes, for example if results need to be used in a calculation instead of printed. Printing in a method isn't inherently wrong, though. It just ties that method to one way of presenting the result.

Reply to this answer
Dossick

You don't have to choose between your structure and the manual's exactly. A method could accept a number of rolls and return a list. Then the caller could print that list or do something else with it.

A single-roll method is still a handy building block for that. The manual repeats the collection code for each die, so there is room to reduce repetition there too.

Reply to this answer
w83!shoelace_2

One small detail: both versions use randint with 1 and the number of sides as the endpoints, so both can produce any whole number from 1 through that number. Assuming randint is imported and the class is indented correctly, your loop does generate ten results.

For this exercise, check whether the instructions specifically require roll_die to return a single value. If they do, matching the printed output alone doesn't meet that part of the requirement.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions