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

Why is my while loop not breaking when it should

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

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

您没有从您的函数返回 'totalhits'。 因此,每次比较 'totalhits' 的值时,都是在将它与初始值 0.

进行比较

您可以将 for 循环更改为

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

得到想要的结果。

  • 您需要捕获从 baseball.Or 返回的值,使用 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.")