user.234
user.234

Reputation: 11

While loop while rolling dice

I am trying to use a while loop instead of a for loop while rolling dice. I do not think elif is right, but I cannot figure out how to use the while loop within this. This is what I have so far:

import random

def rolldiewhileloop():
    number = 10
    one = 0
    two = 0
    three = 0
    four = 0
    five = 0
    six = 0
    while number > 0:
        flip = int(random.random() * 6)
        if(flip == 1):
            one = one + 1
        elif flip == 2:
            two = two + 1
        elif flip == 3:
            three = three + 1
        elif flip == 4:
            four = four + 1
        elif flip == 5:
            five = five + 1
        elif flip == 6:
            six = six + 1

    return [one, two, three, four, five, six]

Upvotes: 0

Views: 2588

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208545

In your current while loop you aren't changing the value of number, so this will be an infinite loop. Since you are starting at 10 and looping until number is less than or equal to zero, you should probably be decrementing by one on each iteration:

number = 10
while number > 0:
    number -= 1
    # the rest of the loop

Note that number -= 1 is equivalent to number = number - 1.

As a side note, instead of multiplying the result of random.random() it would be better to use random.randint(1, 6). Also, since you are returning an array already it would be more Pythonic to create a list of the results and modify that, rather than creating a separate variable for each possibility. For example:

def rolldiewhileloop():
    results = [0] * 6
    number = 10
    while number > 0:
        number -= 1
        flip = random.randint(1, 6)
        results[flip-1] += 1
    return results

Upvotes: 6

Eric Andres
Eric Andres

Reputation: 3417

You need to decrement number on each pass of the while loop. Put number -= 1 as the last line in the while loop.

Upvotes: 1

Related Questions