gpt4 book ai didi

python - 为什么我的 while 循环在应该中断时却没有中断

转载 作者:行者123 更新时间:2023-12-01 06:54:14 33 4
gpt4 key购买 nike

我目前正在尝试制作一个程序来运行模拟,其中棒球运动员有 81% 的机会击中球,目标是棒球运动员连续击中 56 次。我将其设置为将运行一百万次重复,但如果玩家连续命中 56 次或更多,它应该停止,并打印玩家连续命中 56 次的尝试次数。然而,由于某种原因,当总命中数至少为 56 时,我的 for 循环不会停止(预测概率远低于 1/1000000)。为什么我的循环没有正确中断?

import random
attempts = 0
totalhits = 0
def baseball():
totalhits = 0
hit = 1
while hit == 1:
odds = random.randint(1,100)
if odds <= 81:
hit = 1
totalhits = totalhits + 1
else:
hit = 0
return totalhits

for i in range(1,1000000):
baseball()
if totalhits >= 56:
break
attempts = attempts + 1

print("Attempt " + str(attempts) + " succeeded.")

结果是一致的尝试999999成功

最佳答案

  • 您需要捕获从棒球返回的值。或者使用global
  • 您在 baseball 函数中使用的变量 totalhits 与您在全局级别声明的不同。
  • 阅读有关 Python 中变量作用域的更多信息,以便更好地理解。
import random
attempts = 0
totalhits = 0
def baseball():
totalhits = 0
hit = 1
while hit == 1:
odds = random.randint(1,100)
if odds <= 81:
hit = 1
totalhits = totalhits + 1
else:
hit = 0
return totalhits

for i in range(1,1000000):
totalhits = baseball()
if totalhits >= 56:
break
attempts = attempts + 1

print("Attempt " + str(attempts) + " succeeded.")

解决方案 2:使用global

import random
attempts = 0
totalhits = 0
def baseball():
global totalhits
totalhits = 0
hit = 1
while hit == 1:
odds = random.randint(1,100)
if odds <= 81:
hit = 1
totalhits = totalhits + 1
else:
hit = 0

for i in range(1,1000000):
baseball()
if totalhits >= 56:
break
attempts = attempts + 1

print("Attempt " + str(attempts) + " succeeded.")

关于python - 为什么我的 while 循环在应该中断时却没有中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58880244/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com