gpt4 book ai didi

python - 在 While 循环中访问全局 VAR 时出现问题

转载 作者:行者123 更新时间:2023-11-30 23:37:35 24 4
gpt4 key购买 nike

抱歉,这是一个愚蠢的问题。这些解决方案对于使用全局变量是正确的,但我的代码还有其他问题。

这是代码片段。我正在研究 6.00x MIT 类(class)中的问题 3/问题集 2。

paymentFound = False

while paymentFound == False:
global paymentFound
testMid = findMid(newMin, newMax)
testStatus = testPayment(testMid)
if testStatus == "done":
paymentFound = True
print "Lowest Payment: ",testMid
elif testStatus == "high":
newMax = testMid
elif testStatus == "low":
newMin = testMid

这是我收到的错误:pset1.3.py:32: SyntaxWarning: 在全局声明之前分配名称“paymentFound” 全局支付发现

我在某处读到,如果全局变量对“for”循环很重要,则不能使用全局变量,但我不知道这在 while 循环中是否重要。

对于为什么我会收到此错误有什么想法吗?

抱歉,必须重新编辑代码,使其看起来更美观。

最佳答案

错误消息描述了该错误:您的“全局”命令太晚了。试试这个:

global paymentFound
paymentFound = False

while paymentFound == False:
testMid = findMid(newMin, newMax)
...

关于python - 在 While 循环中访问全局 VAR 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15399752/

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