Search code examples
pythonfunctionrandomdice

How can i sort a function?


What i want to do with this code is roll 'n' number of dice and then find the lower quartile of it.

so far i have:

from random import randint
#Rolling the Die

numofdie = int(input("Please input the number of dice u want to roll: "))

if numofdie < 1:
  print ("PLease enter 1 or more")
  quit()
if numofdie > 100:
  print ("PLease enter a number less than 100")
  quit()

#Sum

def dicerolls():
    return [randint(1,6) for _ in range(numofdie)]
print (dicerolls())

Then i used the string.sort() function to try and sort the dicerolls() but realised that it will not work as it is a function. How can i fix this and consequently be able to find the lower quartile.

Thanks


Solution

  • Put the result in a variable, then sort that.

    rolls = dicerolls()
    rolls.sort()
    print(rolls)
    

    Or use the sorted() function:

    print(sorted(dicerolls())