简体   繁体   中英

Why python's global variable can not be used in other functions?

I want to receive string data from server continuously using while loop and thread and then I want to do something use this string data that I receive from server so I have decided to use global variable.

But when I use global variable, python says this variable is not defined. I have tried to solve this but I still don't know why. I hope you help me. Thank you for reading.

global order
def receive():
    while True:
        order = client.recv(1)
        order = order.decode()

def execution():
    if order == "1":
        print("1")
    elif order == "2":
        print("2")

receiver = threading.Thread(target=receive, args=())
receiver.start()

execution()

result: order is not defined.

You're using global the wrong way. Try this instead:

order

def receive():
    global order
    while True:
        order = client.recv(1)
        order = order.decode()

def execution():
    global order
    if order == "1":
        print("1")
    elif order == "2":
        print("2")

receiver = threading.Thread(target=receive, args=())
receiver.start()

execution()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM