Garry Hurst
Garry Hurst

Reputation: 103

i want to create a function to roll a set number of dice thru the num variable in pythonic way

My question is how do i get the list roll to print 6 numbers?

import random
from random import *
num = 6

def d6(num):
  for x in range(num):
  roll = randint(1,6)
  print ("", roll)
print("finished you rolled: ",roll)

Upvotes: 1

Views: 1812

Answers (3)

Rob Watts
Rob Watts

Reputation: 7146

You can do this all in a single list comprehension:

import random

def d6(num):
    return [random.randint(1,6) for i in range(num)]

print d6(6)

If you want, it's pretty easy to modify this so that you can use n-sided dice:

import random

def rolldice(num, sides=6):
    return [random.randint(1,sides) for i in range(num)]

print rolldice(5) # roll 5 six-sided dice
print rolldice(6, 20) # roll 6 20-sided dice

If you have a situation where you might throw mixed dice, you could input those as a list:

import random

def rolldice(dice):
    return [random.randint(1, die) for die in dice]

print rolldice([6, 6, 20, 100, 20])
# Example output - [5, 1, 9, 84, 13]

Upvotes: 2

user3473949
user3473949

Reputation: 205

You can append each roll to an array, and then print the array.

import random
from random import *
num = 6

def d6(num):
    rolls = []
    for x in range(num):
            rolls.append(randint(1,6))
    print rolls

>>> d6(5)
[4, 6, 1, 1, 1]

`

Upvotes: 0

merlin2011
merlin2011

Reputation: 75585

I am going to hazard a guess that you are trying to print the rolls on a line after your message.

import random
from random import *
num = 6

def d6(num):
    rolls = []
    for x in range(num):
        rolls.append(randint(1,6))
    return rolls

rolls = d6(6);
print("finished you rolled: ",rolls)

Alternatively, you can print space-delimited as follows.

print("finished you rolled: " + " ".join(str(x) for x in rolls))

Upvotes: 0

Related Questions