spikeymango
spikeymango

Reputation: 67

Trouble accessing Global VAR in While Loop

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.

Upvotes: 2

Views: 8217

Answers (2)

zds_cn
zds_cn

Reputation: 288

you should 'global' it out of the loop like this:

global paymentFound
paymentFound = False

while ~:
    yourcode

i happen to meet this problem before.

i tried this codes and it did work:

global a 
a = 1

while a :
    if True:
        a = 0
    print('is it?')

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168626

The error is described by the error message: Your "global" command is too late. Try this:

global paymentFound
paymentFound = False

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

Upvotes: 3

Related Questions