简体   繁体   中英

i am getting local variable referenced before assignment when i use that variable in try-except block

i am getting

local variable 'flag' referenced before assignment

in python. what am i doing wrong here?

flag = 0
def abc():
    while flag <= 10:
        try:
            print(10/0)
        except Exception:
            print('yo')
            flag += 1

abc()
flag = 0
def abc(argument):
    while argument <= 10:
        try:
            print(10/0)
        except Exception:
            print('yo')
            argument += 1

abc(flag)
def abc():
    flag = 0
    while flag <= 10:
        try:
            print(10/0)
        except Exception:
            print('yo')
            flag += 1
    return flag

abc()

I'd use this.

It's not a matter of referencing that variable in a try/catch, it's a matter of defining that variable outside the function you used it in. flag is declared outside of abc() and is not declared as global; therefore, python doesn't believe there's a variable named flag inside the function that it can use. (If I'm correct, flag is declared as being part of __main__ , since you can print it below the call to abc() without issue.)

If you intended to use flag as nothing more than a counter, moving it inside the def works:

def abc():
    flag = 0
    while flag <= 10:
        try:
            print(10/0)
        except Exception:
            print('yo')
            flag += 1

abc()

If, however, you intended to use it elsewhere, you would have to either declare it as global ( not recommended) or declare it as a local variable and then return it. If it's defined externally, consider passing it in as a parameter to abc .

You are a victim of variable scoping in Python. What you need is the global keyword ( great tutorial on the subject ). In this case:

flag = 0

def abc():
    global flag
    while flag <= 10:
        try:
            print(10/0)
        except Exception:
            print('yo')
            flag += 1

abc()

Note the new global flag line at the beginning of abc 's definition. This tells the function that the keyword flag should come from the global scope, not the local scope.

As a side note, it is generally considered bad practice to use global variables, so I would recommend you think about your overall design. There are definitely valid times to use global , however, try to avoid it when possible.

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