Search code examples
pythondice

Why is my for loop being ignored?


import random
stats = [0]*6
fixed = [1,2,3,4,5,6]
def single_roll(n,fixed=(),sides=6):
    for x in range(0,n):
        dice = random.randint(1,6)
        if dice == 1:
           stats[0] += 1
        elif dice == 2:
           stats[1] += 1
        elif dice == 3:
           stats[2] += 1
        elif dice == 4:
           stats[3] += 1
        elif dice == 5:
           stats[4] += 1
        elif dice == 6:
           stats[5] += 1
x = list(zip(fixed, stats))
single_roll(10)
print (x)

When I try and run this, why does it produce a list with 0's for the stats list? Why is my for loop not being used in the program? Thanks.


Solution

  • You're creating x before calling your single_roll function, and at that point the stats list is all zeroes. stats is used to compute the value of x, but afterwards x is a brand new list with no connection to stats, so even though single_roll modifies stats, x doesn't change. You can just put the assignment after the call:

    single_roll(10)
    x = list(zip(fixed, stats))