Search code examples
pythonrandomdiceaccumulator

Python: random module with sum accumulator for odd numbers


Hello I'm trying to make a function including the random module that only accumulates the sum of odd rolls of n-dice, n-sided times. Sounds a little confusing but for example if I rolled 2-sided die 2 times and got 1 and 2, the result would be only 1 (since 2 is even). Here's what I have:

import random

def roll(sides, dice):
    y = 0
    for i in range(1, dice+1):
        if y%2 == 1:
            y = y + random.randrange(1, sides+1)
    return y

How can I get this to work? It never gets past the first if because it starts at y=0


Solution

  • In your code, the problem is that you add a random number before checking if it's odd or even in your for loop.

    I think you're looking for something like this:

    def roll(sides, times):
        final_sum = 0
        for i in range(times):
            randnum = random.randrange(sides)
            final_sum += randnum if randnum % 2 else 0
        return final_sum