This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Iterating over inconsistently-indented code block causes execution of code only on last iteration of loop
Type: enhancement Stage: resolved
Components: Interpreter Core Versions: Python 2.7
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: Nosy List: dimitriprosser, mark.dickinson, nedbat
Priority: normal Keywords:

Created on 2012-11-28 16:02 by dimitriprosser, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
python_test.py dimitriprosser, 2012-11-28 16:01 Source file that recreates this error
Messages (4)
msg176551 - (view) Author: Brian Berard (dimitriprosser) Date: 2012-11-28 16:01
When a loop (for loop in this case) contains multiple lines of code, if the lines are inconsistently indented, the for loop will only execute those lines on the final pass through the loop with no type of warning regarding indentation error. 

Ex. 

for i in range(0,10):
    print "I will print on every iteration: %d" % i  # TAB indented
    print "I will only print on the final iteration: %d" % i # 4 spaces
msg176552 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2012-11-28 16:39
This is expected behaviour for Python 2.x:  Python interprets every TAB character as advancing to the next multiple-of-8 column, regardless of how your editor sees it.  It would be too disruptive to change this behaviour in Python 2.x.

It's already fixed in Python 3: there it's a syntax error to mix tabs and spaces in this way.  Python 2.7 gives a warning if you run with the '-3' flag.
msg176562 - (view) Author: Ned Batchelder (nedbat) * (Python triager) Date: 2012-11-28 18:10
@Brian:  Your code doesn't run in Python 2.7 as you've shown it, it produces an IndentationError.  If your code is actually different, and does run, try running it with the -tt flag on Python, which will warn about inconsistent indentation.
msg176563 - (view) Author: Brian Berard (dimitriprosser) Date: 2012-11-28 18:19
@nedbat I'm able to run that code as is and receive no such error. With the -tt option, I do receive an indentation error. I will keep that in mind.
History
Date User Action Args
2022-04-11 14:57:38adminsetgithub: 60775
2012-11-28 18:19:01dimitriprossersetmessages: + msg176563
2012-11-28 18:10:56nedbatsetnosy: + nedbat
messages: + msg176562
2012-11-28 16:41:06serhiy.storchakasetstage: resolved
2012-11-28 16:39:46mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg176552

resolution: wont fix
2012-11-28 16:26:46dimitriprossersettype: behavior -> enhancement
2012-11-28 16:02:00dimitriprossercreate