python - 在循环时更改 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 超出numRolls
了for
范围。我想出的替代解决方案意味着绝对无穷无尽的单独卷。在 1 和 5 之间随机选择不是一个可行的选择.. :)
有人可以在这里指出我正确的方向吗?
解决方案
使用 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()
并向其传递参数0
和numRolls
. 然后给你一个你迭代range()
的生成器(我们称之为生成器)。rollsGenerator
创建此生成器的目的是为您0
提供numRolls-1
包容性的价值。
因此,您的 for 循环有效地评估为for i in rollsGenerator
在第一次迭代开始之前。
然后,在循环内部,当您增加 的值时numRolls
,它不会改变迭代次数,因为rollsGenerator
已经使用 的原始值创建了numRolls
。for 循环不会range(0,numRolls)
在每次迭代时调用,因此无论您如何更改生成器都会保持不变numRolls
。
通过使用 while 循环,您基本上是在更改代码以检查numRolls
每次迭代的最新值,并且您跳过了整个生成器业务。
推荐阅读
- gams-math - 如何定义并集、交集、对称差?
- c# - c# 如何以编程方式加载具有相同命名空间的外部程序集
- javascript - JavaScript 承诺不会按顺序触发
- asp.net-core - Asp.net core 2.0 本地化在部分视图中不起作用。
- ios - 无法在自定义时间 ios 目标 c 上触发 UILocalNotification
- google-apps-script - 如果存在手动添加的安装触发器,ScriptApp.getUserTriggers 会给出服务器错误
- javascript - 获取对我的 React 应用程序的 API 请求
- wav - NAO 记录缓冲区的采样率不匹配
- python - Pandas 在比较 2 个数据帧时如何检查行来自哪个数据帧?
- oracle - Oracle 无法执行 dml 操作 无法在查询中调用