Reputation: 894
I'd like to create code that will 'roll' number_of_dice times and find the sum of the rolls. This is what I have. I'm getting an error when I do "sum = sum + roll" that there's unsupported operand types for +: built_in_function_or_method and int. How can I solve this?
for i in range(0,number_of_dice):
roll = random.randint(1,number_of_sides + 1)
sum = sum + roll
return sum
Upvotes: 1
Views: 7751
Reputation: 776
I'd use:
import random
def sum_of_dice(number_of_dice, n_sides_on_die=6):
return sum([random.choice(range(1, n_sides_on_die + 1))
for i in range(number_of_dice)])
Upvotes: 0
Reputation: 46027
Python has a built in function sum
that returns the sum of numbers given as a sequence. Since you have not declared a variable sum
it is trying to +
that built in function and a number roll
which is not permitted. You need to define the variable before the loop:
sum = 0
for i in range(0,number_of_dice):
roll = random.randint(1,number_of_sides + 1)
sum = sum + roll
return sum
Note that you are supposed to return after the loop, not from inside the loop. Also, if you don't want to shadow the built in function sum
then you can use a different name for your variable.
Upvotes: 2