Careful with Python indentation

If you are like me, using the default Python integrated development environment, IDLE, you probably feel like me, desiring more features, such as line numbers, horizontal scrolling, code folding, etc. I am aware of a Python module called IDLEX, which has lots of these features. On the other hand, if you are already familiar with text editors such as Notepad ++ (Npp in short), which is excellent, you may want to just switch over to Npp for your Python script editing. You can either use their default color theme or edit it to look like IDLE. There is an essential feature you need to set in order to produce correct indentation though.

Because unlike other major programming languages such as C/C++, Java, etc. Python uses indentation to indicate structure. If you write an if-statement, you do this:

[sourcecode language=”python”]

if (statement==True):
print(‘It is true!’)
else:
print(‘It is not true!’)

[/sourcecode]

I’ve learned a lesson of mixing tab characters and white spaces as indentation. It’s a bad mix. Although I love the tab character more than spaces, I consider spaces better in Python since it is the Python standard. Here is some tab vs. space discussion. They each have advantages. So how do we set up Npp to produce the Python standard 4-spaces whenever we press the TAB key on the keyboard? Here it is:

This “Preferences” dialog is under “Settings” menu. Just make sure you select “Language” on the left and then “Python” on the right (not the middle), deselect “use default value”, and select “Replace by space”. This produces Python 4-space indentations. Once you’re done, you may want to inspect your exist script to see if there are any tabs by selecting option “Show all characters” under “View” menu’s “Show Symbol” option. This way tab characters look like red arrows while white spaces look as red dots.

Now you are using Npp for editing, you can create a “Run” command inside Npp to run your Python code:

Under “Run” menu “Run…” option, you can type up the command python -i “$(FULL_CURRENT_PATH)”

Save a short cut such as Shift + F5. Then you can run the code with the shortcut.

2 Responses to Careful with Python indentation

  1. Jeff says:

    I’ve used Idle as well as many (many) text editors for Python code over years, and I was blown away by PyCharm after a few minutes. You won’t go back!

    • liudr says:

      Thanks Jeff. I’ll give PyCharm a try. Currently I am using Npp and have started experimenting on Atom code editor. I’m always interested in a light-weight and customizable editor that works on all major operating systems. IDLE meets some of my needs but doesn’t offer enough features.

Leave a Reply

%d