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"
If you try to update a variable that doesn't exist, you get an error because Python evaluates the expression on the right side of the assignment operator before it assigns the resulting value to the name on the left. Before you can update a variable, you have to initialize it, usually with a simple assignment.
In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.
Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).
The use of global variable in python is considered bad practice and should generally be avoided. Instead the user can try and use a parameter for passing a value onto a function or return a value to obtain it.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With