r/pythonhelp • • Nov 11 '21

Unindent does not match any outer indentation level

I'm making aprogram that takes a text file and generates a dictionary where the keys are the words and the values are the number of occurrences of each word.

However when I run the program it either switches between IndentationError: unindent does not match any outer indentation level or UnboundLocalError: local variable 'word' referenced before assignmentwhen I add or remove indentations from one part of the program.

I've seen others face similar issues and they suggested replacing spaces with tabs, but I've tried that and the error persists. Why does it not just work??

0 Upvotes

1 comment sorted by

2

u/Remarkable-Avocado44 Nov 11 '21

Your variables need to be created in the code before they can be used. “Before” means somewhere above whatever line wants to use it.

If you are using functions at all, this gets tricky - indentations are used to identify what code exists as the function body. Changing indentation levels could be the difference between a variable searching for its value within the function body, or within the global namespace(the regular code, not within the function)

Long story short- if you use a variable , make sure you assign it somewhere in the code space above whatever line is calling it.

Make sure your code is lined up;

Look out for other errors, like open parens … sometimes a closed paren left off a line will cause other errors to be thrown