Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting a weird 'local variable referenced before assignment' error

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve changed xxx name to other random names – same error.

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading