如何编辑Python代码 How To Edit Python Code

Python uses an indentation-based syntax for grouping statements into blocks. For example:


if some_condition and some_other_condition

However, beginners to Python programming are sometimes worried about this aspect of the language, asking questions like...


This leads us to introduce the golden rule...


不要混合使用Tab和空格! Do Not Mix Tabs and Spaces!

Now, this doesn't mean that you can't use the Tab key on your keyboard: it just means that your editor has to be set up properly so that tab characters aren't mixed in with space characters. Tab characters often appear as very wide spaces in text, typically making the cursor jump to a position further across in the editor window or terminal.


This leads us to a simple choice:


Many people recommend the first choice since you can use the Tab key as much as you like, and it does no harm to add spaces manually, although your indentation must always be consistent.


Whilst there is always a risk that someone with a badly behaved editor will start mixing tabs and spaces, potentially confusing Python, it should be remembered that such editing habits will probably confuse programmers working with such code in any language, as is shown by the following classic example in C-like languages:


if (some_condition && some_other_condition)

Although a C or C++ compiler will accept something like this, there may be a clear mismatch between what the programmer intended and the behaviour of the resulting code. Clearly, "sloppy" editing habits have an impact regardless of the role of indentation in a language's syntax.


文本编辑器的选择 Choosing a Text Editor

You may have a favourite text editor which you want to use to edit Python code. Hopefully, this editor will be slightly more sophisticated than the Notepad editor (on Windows) and will let you change its settings so that Python code can be edited effectively. Many text editors have support for syntax highlighting (so that different aspects of the text have different colours - keywords might be yellow, strings might be purple, and so on), and such things can be worthwhile benefits which can lure you away from more primitive (if more familiar) programs. A list of Python-compatible editors can be found on the PythonEditors page.


配置文本编辑器Configuring a Text Editor

Now that you've made a choice from the PythonEditors list, you'll want to make sure that it is set up properly. Below you'll find a guide for a number of different editors dealing with important Python issues such as indentation (tabs and spaces) as well as other more general issues like encodings and syntax highlighting/colouring.


编者注释Editorial Note

Feel free to add entries about other editors in the section above. Try to arrange the entries in ascending alphabetical order.


其它资源Other Resources


EditPythonCodeChinese (last edited 2011-08-25 03:14:27 by 221)

Unable to edit the page? See the FrontPage for instructions.