Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 252
Rhys Avatar asked Jul 28 '13 19:07

Rhys


People also ask

Why variable is not updating in Python?

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.

Can you update a global variable in Python?

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.

Can global variables be updated?

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).

Should you avoid using global variables in Python?

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.


1 Answers

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.

like image 184
unutbu Avatar answered Oct 02 '22 22:10

unutbu