0

I'm trying to make a basic dice roller. When i run this program in Codeskulptor, it throws an error on the randint function. Can I not set the range for it using raw_input plugged into variables? Is there a different function I should use?

"""Program to roll random numbers within the ranges set."""

import random
sides_of_die=raw_input("Enter how many sides your die has: ")
number_of_dice=raw_input("Enter number of dice you have: ")
total=sides_of_die*number_of_dice
rollinput=raw_input("Would you like to roll now?")
rollinputcap=rollinput.upper()
if rollinputcap =="Y":
    print random.randint(number_of_dice,total)
else:
    print "What do you want then?"
1
  • 2
    The distribution of multiple dice is not the same as the the distribution of sides*number, you need to get a random number for each die and add them if you want to be accurate. Commented Sep 15, 2013 at 1:34

3 Answers 3

2

raw_input() returns a string, not an integer. To convert it to an integer type, use int():

sides_of_die = int(raw_input("Enter how many sides your die has: "))
number_of_dice = int(raw_input("Enter number of dice you have: "))

What's happening in your code is, you may input "6" and "2", so when you do total = sides_of_die * number_of_dice, you're getting a TypeError

Sign up to request clarification or add additional context in comments.

Comments

2

This is just because raw_input returns a string, not a number, while randint accept two numbers as arguments

so you should do

total = int(raw_input(..))

Point is, this is not always secure. Exceptions are very likely to be thrown, so you might want to use a try block; but for the time being, I think it's okay (I'm assuming you're just learning Python).

Another thing, which is rather important:

Look at the exception! If you'd read it, you would have known exactly what the problem was.

Comments

1

Beside the raw_input() problem pointed out by the others, @Mark Ransom's comment is important: the sum of dice value eventually follows normal distribution. See: http://en.wikipedia.org/wiki/Dice#Probability

Your:

if rollinputcap =="Y":
    print random.randint(number_of_dice,total)

should be changed to

if rollinputcap =="Y":
    sum_dice=[]
    for i in range(number_of_dice):
        sum_dice.append(random.randint(1, sides_of_dice))
    print sum(sum_dice)

1 Comment

You can shorten the summation considerably with a generator expression: sum(random.randint(1, sides_of_die) for n in range(number_of_dice))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.