Is There A Random Function In Python That Accepts Variables?
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.
Solution 1:
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=0final=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
Solution 2:
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.
Solution 3:
Try randrange(1, 5)
Solution 4:
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 = 6print random.randint(1, sides)
Post a Comment for "Is There A Random Function In Python That Accepts Variables?"