同时滚动骰子循环

时间:2013-10-04 20:02:33

标签: python while-loop

我在滚动骰子时尝试使用while循环而不是for循环。我不认为elif是正确的,但我无法弄清楚如何在其中使用while循环。这就是我到目前为止所做的:

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]

2 个答案:

答案 0 :(得分:6)

在您当前的while循环中,您不会更改number的值,因此这将是一个无限循环。由于您从10开始并循环直到number小于或等于零,因此您应该在每次迭代时减1:

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

请注意,number -= 1相当于number = number - 1

作为旁注,不要将random.random()的结果相乘,而是使用random.randint(1, 6)会更好。此外,由于您已经返回一个数组,因此创建结果列表并修改它会更加Pythonic,而不是为每种可能性创建单独的变量。例如:

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

答案 1 :(得分:1)

你需要在while循环的每次传递中递减数字。将number -= 1作为while循环中的最后一行。