Home > Software design >  Getting a weird 'local variable referenced before assignment' error
Getting a weird 'local variable referenced before assignment' error

Time:02-21

Here's the code - it's a class method.

    def update(self,xxx):
        print("update="   str(xxx))
        
        str = "{:.2f}".format(xxx)

getting error on the print statement.

NameError: local variable referenced before assignment

I've changed xxx name to other random names - same error.

If I comment out the format statement - then no error.

CodePudding user response:

The problem isn't with the xxx parameter, but with the local str variable.

The intent of the code isn't entirely clear to me, but if you rename the str variable to something else (foo, for example), it should work:

def update(self, xxx):
    print("update="   str(xxx))

    foo = "{:.2f}".format(xxx)

By the way, I would caution against using str (and the names of other built-ins like input etc.) as variable names. It makes the code less clear. It also shadows built-ins, causing strange behavior when you try to use said built-ins.

CodePudding user response:

Change str to string or another variable name

Your second variable "str" cannot be this is because the prebuilt function "str()" exists in python. It might confuse your code on what's happening and assume that you are trying to reassign str from a built-in function into something else.

  • Related