首页 > 解决方案 > 在循环时更改 for 循环中的值

问题描述

我被困在一个骰子练习上。对于每个掷出 6 的骰子,需要将它们排除在计数之外并再次掷出。问题是我不知道如何在for range循环时更改循环的值,而且我不知道如何攻击它。这是我所在的位置:

numRolls = 10
initSum = 0

for i in range(0,numRolls):
    diceScore = random.randint(1,6) 
    if(diceScore == 6):
        print("You rolled a 6! You receive two extra rolls.")
        numRolls = numRolls + 2
        # Not making its way to the top of the for-loop
    else:
        totalSum = initSum + diceScore
print("Done! You've rolled a total of ",totalSum)
totalSum = 0

我猜-loop 超出numRollsfor范围。我想出的替代解决方案意味着绝对无穷无尽的单独卷。在 1 和 5 之间随机选择不是一个可行的选择.. :)

有人可以在这里指出我正确的方向吗?

标签: python

解决方案


使用 while 循环并在循环外初始化计数器。然后根据需要在循环内增加计数器和 numRolls

numRolls = 10
rollsSoFar = 0
initSum = 0

while rollsSoFar <= nulRolls:
    diceScore = random.randint(1,6) 
    if(diceScore == 6):
        print("You rolled a 6! You receive two extra rolls.")
        numRolls = numRolls + 2
    else:
        totalSum = initSum + diceScore
    rollsSoFar += 1
print("Done! You've rolled a total of ",totalSum)
totalSum = 0

编辑:添加了为什么这有效的解释

当您创建一个 for 循环时,就像for i in range(0,numRolls)您正在调用函数range()并向其传递参数0numRolls. 然后给你一个你迭代range()的生成器(我们称之为生成器)。rollsGenerator创建此生成器的目的是为您0提供numRolls-1包容性的价值。

因此,您的 for 循环有效地评估为for i in rollsGenerator在第一次迭代开始之前。

然后,在循环内部,当您增加 的值时numRolls,它不会改变迭代次数,因为rollsGenerator已经使用 的原始值创建了numRolls。for 循环不会range(0,numRolls)在每次迭代时调用,因此无论您如何更改生成器都会保持不变numRolls

通过使用 while 循环,您基本上是在更改代码以检查numRolls每次迭代的最新值,并且您跳过了整个生成器业务。


推荐阅读