Skip to content
Advertisement

UnboundLocalError: local variable referenced before assignment doesn’t work in command line call

I am aware that there are many solutions to this kind of question. However, none of them seems to have helped with my case. This is the code I’m referring to:

JavaScript

When I try this code in PyCharm, it works without problems. However, if I use it via command line call it gives this error:

JavaScript

Of course, for the command line call I import sys and use sys.argv as an argument for length. I have tried adding global max_word at the beginning of the function, but it does not work. I have not assigned any variable like max_word before this function.

Advertisement

Answer

Add some error checking to the function to help you debug:

JavaScript

(I simplified the implementation a bit just for my own benefit in making it easier to understand — I’m pretty sure it does the same thing with less confusion.)

Note that adding type annotations also means that if you had a line of code like, say:

JavaScript

if you were to run mypy it would tell you about the error, no assert required:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement