One thing your script is missing, is a function. Functions are extremely useful, and adding a simple one here will be a vital lesson that'll clean up your code. Consider the inner loop you have. It could be changed into a function that returns a list of 4 random rolls, so instead of nesting you call the function, like this:
def roll_dice(number_of_dice):
rolls = []
for _ in range(number_of_dice):
roll = random.randint(1,6)
rolls.append(roll)
return rolls
for _ in range(7):
rolls = roll_dice(4)
stat = sum(rolls) - min(rolls)
stats.append(stat)
Now your code is neater, not to mention easier to read and reusable. If you wanted to roll 5 or 6 dice you still can with the same code. Also you could easily add another parameter for number_of_sides
so you could roll anything instead of just 6 sided die.
Note I also replaced i
and j
with _
as it's Pythonic to use an underscore to denote a throwaway value. In your case you only need range
for the purpose of looping, so you can throw away the values you're getting.
This may be advanced for your kids, but I'll suggest it anyway as it's very useful. Python has list comprehensions, which are basically for loops condensed into expressions that build a list. For roll_dice
you could condense your whole loop like this:
rolls = [random.randint(1, 6) for _ in range(number_of_dice)]
This cuts down on a lot of lines and to me reads practically like a sentence.
rolls equals random integer 1-6 for each value in range 1-number_of_dice
You could make a very short and efficent function this way:
def roll_dice(number_of_dice):
return [random.randint(1, 6) for _ in range(number_of_dice)]
Brevity isn't always the best way to go, but when it reads clearly (as this does to me) it's very useful.