为什么列表是空的?

时间:2021-07-15 19:06:17

标签: python list for-loop

每次掷骰子时,应将当前位置添加到列表中 这不会发生,位置每次都重置为

import random as ran


def dice_trial(n):
    pos = 1
    values = []

    for pos in range(n):
        pos = ran.randint(0, 6) + ran.randint(0, 6)

        if pos > 40:
            pos -= 40
            str(pos).join(values)
        
        else:
            str(pos).join(values)
        
    print(values)

def main():
    n = input('How many times the dice will be rolled? ')

    try:
        n = int(n)
        dice_trial(n)
    except ValueError:
        main()

main()

我刚刚解决了它,我真的要感谢 Ben Y. 的帮助和 其他人的帮助

import random as ran


def dice_trial(n):
    pos = 1
    values = []

    for i in range(n):
        pos = pos + ran.randint(0, 6) + ran.randint(0, 6)

        if pos > 40:
            pos -= 40
            values.append(str(pos))
        
        else:
            values.append(str(pos))
        
    print(values)

def main():
    n = input('How many times the dice will be rolled? ')

    try:
        n = int(n)
        dice_trial(n)
    except ValueError:
        main()

main()

详情?比如什么?

1 个答案:

答案 0 :(得分:0)

我会尝试清理它,但希望您能从我所做的清理工作中吸取教训。

import random as ran


def dice_trial(n):
    values = []

    for _ in range(n):  # Repeat n times
        values.append(ran.randint(0, 6) + ran.randint(0, 6))
    print(values)

def main():
    n = True
    while n:  # 
        n = input('How many times the dice will be rolled? (0 to quit) ')
        try:
            n = int(n)
        except ValueError:
            print("{} is not a number".format(n))
            continue
        dice_trial(n)
main()