Nested for loops and print statements
Steve D'Aprano
steve+python at pearwood.info
Mon Sep 26 13:06:32 EDT 2016
On Tue, 27 Sep 2016 01:25 am, Cai Gengyang wrote:
> I just wanted to note that sometimes the code works, sometimes it doesn't.
> (even though both are exactly the same code) ... Weird , dum dum dum
They are not the same code. One of them mixes tabs and spaces for the same
indent level, the other does not.
Here is a hint how you can tell the difference between lines with tabs and
lines with spaces in the Python interactive interpreter:
- if you pressed the spacebar repeatedly to get the indent, like
SPACEBAR SPACEBAR SPACEBAR SPACEBAR, then the line will be indented
with spaces;
- if you pressed the tab key to get the indent, like TAB TAB, then the
line will be indented with tabs;
- if you pressed the tab key first, then spaces, like TAB SPACEBAR,
then the line will be indented with a mixture of tabs and spaces.
If you are copying code from a text editor, check your editor's settings.
Some editors will be configured to insert spaces when you press the tab
key.
Your first example has:
1st line: no indent
2nd line: seven spaces
3rd line: tab + two spaces
Notice that the 2nd and 3rd line start with inconsistent indentation: one
uses spaces, the other uses tab. This is bad.
Your second example has:
1st line: no indent
2nd line: tab
3rd line: tab + three spaces
Notice that the 2nd and 3rd line start with the same indentation: both start
with a tab. This is better, it is enough to satisfy the interpreter, but it
would be better if you picked one (spaces) or the other (tabs) and ONLY
used that. Other wise you will just confuse yourself.
But you won't confuse the interpreter.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list