2

Sorry, this was a dumb question. The solutions are correct for using global variables, but there was just something else wrong with my code.

Here's a snippet of the code. I'm working on Problem 3/Problem Set 2 form the 6.00x MIT course.

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

This is the error that I'm getting: pset1.3.py:32: SyntaxWarning: name 'paymentFound' is assigned to before global declaration global paymentFound

I read somewhere that you can't use global variables if they're important to a 'for' loop, but I don't know if this is important in a while loop.

Any thoughts on why I'm getting this error?

Sorry, had to reedit the code so it looks more presentable.

4

2 回答 2

3

该错误由错误消息描述:您的“全局”命令为时已晚。尝试这个:

global paymentFound
paymentFound = False

while paymentFound == False:
    testMid = findMid(newMin, newMax)
    ...
于 2013-03-14T01:49:19.540 回答
0

你应该像这样将它“全局”出循环:

global paymentFound
paymentFound = False

while ~:
    yourcode

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

我试过这个代码,它确实有效:

global a 
a = 1

while a :
    if True:
        a = 0
    print('is it?')
于 2013-03-14T01:53:23.827 回答