在While循环中访问全局变量时出现问题

2024-10-01 15:33:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

下面是一段代码。我正在研究麻省理工学院6.00x课程的习题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循环中是否重要。在

你觉得我为什么会犯这个错误吗?在

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


Tags: 代码false错误解决方案全局课程elifwhile
2条回答

错误信息描述了错误:您的“global”命令太晚了。试试这个:

global paymentFound
paymentFound = False

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

你应该像这样“全局化”它:

global paymentFound
paymentFound = False

while ~:
    yourcode

我以前碰巧遇到过这个问题。在

我试过这些代码,但确实奏效了:

^{pr2}$

相关问题 更多 >

    热门问题