python - 为什么我的while循环在它应该中断的时候没有中断
问题描述
我目前正在尝试制作一个运行模拟的程序,其中棒球运动员有 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.")
结果始终如一
Attempt 999999 succeeded
解决方案
- 您需要捕获从棒球返回的值。或使用
global
. totalhits
您在baseball
函数内部使用的变量与您在全局级别声明的变量不同。- 阅读更多关于 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.")
推荐阅读
- javascript - 汉堡菜单在初始加载时未显示的可访问性问题
- python - 将默认值设置为 ipywidgets - Python
- laravel - Laravel Mollie 付款 - 419 页已过期
- javascript - 模拟键盘输入/将字符串插入文本区域(youtube 工作室)
- git - 如何在 git rebase 之前找出我使用的文件是否已更改?
- javascript - 如何在JS中使用两个for in循环来获取数据
- reactjs - Firebase Firestore onSnapchot 并不总是给我数据
- ios - 从 IOS 相机到 Azure 存储资源管理器的 Ionic 5 Blob 图像(请求发送错误)[在 Android 上工作,而不是 IOS]
- ruby-on-rails - 该文件被 Git 忽略,但不在 .gitignore 中
- python - 如何使用定义的函数两次而不会出错?