What Happens When Your Code Does Not Follow The Python Rules?

So what happens if your code does not follow the Python rules? This article will be fairly short. Most of this will not depend on your version of Python.


So what happens if you get your tab or spacing incorrect? Let’s give it a go. Often times the best way to figure something like this out is to try it out.

for i in range(0,3):
  File "<stdin>", line 2
IndentationError: expected an indented block

So python calls out that our indentation was incorrect. It expects our code formatted a certain way, Python gives you a descriptive error explaining what changes it wants. Let’s implement those changes and see the result.

for i in range(0,3):

Now if we add in some spaces infront of the print, Python stops complaining and works as expected. Interestingly enough we can add as many space as we’d like here and Python will still run the code. The downside to using random numbers of spaces here is that we won’t be able to nest our for-loops very easily. I use my tab button in Pycharm which from my recollection gets translated into 4 spaces. These types of descriptive errors will guide you in the learning process.

What about the PEP 8 rules?

These are important and much less easy to follow than our typical errors like spaces. There’s things like limiting lines to 79 characters, starting inline comments with a # and single space. I hate the monotony of making sure I check a lot of the pep-8 style guide so instead I leverage Black. Black is the self descriped uncompromised Python formatter. It’ll break your long lines of code up. Admittedly it doesn’t do everything for you, but it does do a lot.

You can leave the rest up to something like Pylint. It doesn’t auto-correct any of your smells but it gives you tips on what to change.

How do I use Black?

Installing black in your venv is going to be the best route. Virtual environments are your friend. If you’re not familiar with them yet, then a global install is fine. I’m using an M1 mac by the way.

pip3 install black

I’d then close out of your terminal and open it back up. Black should now work from the terminal. Want to check if things are working? Execute the following:

where black

It should return a folder path that points to Black’s location.

black your_file_name.py

This will format your_file_name.py.

Conclusion – What Happens When Your Code Does Not Follow The Python Rules?

So, what happens if your code does not follow the Python rules? If the error is bad, Python will tell you. If not, Pylint or Black can lend a hand. Having issues with Python? Check this article out. Happy coding!