tags:

views:

200

answers:

4

I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, randint will not accept a variable. Is there a way to do what I'm trying to do?

code below:

import random
a=0
final=0
working=0

sides = input("How many dice do you want to roll?")

while a<=sides:
    a=a+1
    working=random.randint(1, 4)
    final=final+working

print "Your total is:", final
+1  A: 

Try randrange(1, 5)

Generating random numbers in Python

Chris Ballance
+2  A: 

you need to pass sides to randint, for example like this:

working = random.randint(1, int(sides))

also, it's not the best practice to use input in python-2.x. please, use raw_input instead, you'll need to convert to number yourself, but it's safer.

SilentGhost
+1  A: 

random.randint accepts a variable as either of its two parameters. I'm not sure exactly what your issue is.

This works for me:

import random

# generate number between 1 and 6
sides = 6
print random.randint(1, sides)
ataylor
+2  A: 

If looks like you're confused about the number of dice and the number of sides

I've changed the code to use raw_input(). input()is not recommended because Python literally evaluates the user input which could be malicious python code

import random
a=0
final=0
working=0

rolls = int(raw_input("How many dice do you want to roll? "))
sides = int(raw_input("How many sides? "))

while a<rolls:
    a=a+1
    working=random.randint(1, sides)
    final=final+working

print "Your total is:", final
gnibbler