首页 > 解决方案 > 为什么我的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

标签: pythonloopsfor-loopbreak

解决方案


  • 您需要捕获从棒球返回的值。或使用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.")

推荐阅读