Python Global Variable not updating
I'm new with Python and programming but I can't seem to understand why this function does not update the global variable
global weight
weight = 'value'
def GetLiveWeight():
SetPort()
while interupt == False:
port.write(requestChar2)
liveRaw = port.read(9)
liveRaw += port.read(port.inWaiting())
time.sleep(0.2)
weight = liveRaw.translate(None, string.letters)
return weight
I also tried this:
weight = 'value'
def GetLiveWeight():
global weight
SetPort()
while interupt == False:
port.write(requestChar2)
liveRaw = port.read(9)
liveRaw += port.read(port.inWaiting())
time.sleep(0.2)
weight = liveRaw.translate(None, string.letters)
return weight
try:
threading.Thread(target = GetLiveWeight).start()
print liveWeight
except:
print "Error: unable to start thread"
Solution 1:
You need to declare that weight
is global inside GetLiveWeight
, not outside it.
weight = 'value'
def GetLiveWeight():
global weight
The global
statement tells Python that within the scope of the GetLiveWeight
function, weight
refers to the global variable weight
, not some new local variable weight
.