Search code examples
pythondice

Fill a list with 10 rolls of a dice (the roll of a dice can be simulated by getting random integer between 1 and 6)


The assignment says I must display:

Display all 10 rolls
Display all 10 rolls in backwards order
Display the first and last rolls
Display the sum of the rolls
Display the min  and the max value rolled.

The code I have sort of works but I cannot figure out how to get the others to display. I keep getting error codes. Here is what I have so far, I deleted a bit of it because I became frustrated:

import random

def roll(sides=6):
         numRolled = random.randint(1,sides)
         return num_rolled
def rollDice():
         sides = 6
         rolling = True
         diceList=[] 
         while rolling:
                 numRolled = random.randint(1,sides)
                 diceList.append(numRolled)
                 print (numRolled, end="")
                 if len(diceList) == 10:
                    rolling = False
         return diceList

def main ():
    print (rollDice())
    print (diceList)
    print (rolldice.sort())
    print (rollDice[0],rolldice[9])
    print (rolldice.min,rolldice.max)
    print (rolldice.sum)
main()

Solution

  • You can use list comprehension to generate a list fill with 10 rolls of a dice. And then return the result what you want.

    ten_roll_of_dice = [random.randint(1, 6) for _ in range(10)]
    
    print "Display all 10 rolls: ", ten_roll_of_dice
    
    print "Display all 10 rolls in backwards order: ", ten_roll_of_dice[::-1]
    
    print "Display the first and last rolls: %d, %d" % (ten_roll_of_dice[0], ten_roll_of_dice[-1])
    
    print "Display the sum of the rolls: ", sum(ten_roll_of_dice)
    
    print "Display the min  and the max value rolled: %d, %d" %  (min(ten_roll_of_dice), max(ten_roll_of_dice))