Python global variable not updating

Im new with Python and programming, but doesn'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 

also i 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" 
+6
source share
1 answer

You need to declare that weight is global inside GetLiveWeight , and not outside of it.

 weight = 'value' def GetLiveWeight(): global weight 

The global operator tells Python that the GetLiveWeight weight function refers to the global variable weight , and not some new local variable weight .

+12
source

Source: https://habr.com/ru/post/950477/


All Articles