Reputation: 21
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
Upvotes: 0
Views: 5446
Reputation: 304137
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
Upvotes: 3
Reputation: 319551
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.
Upvotes: 2
Reputation: 66059
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)
Upvotes: 1