for loop

paul.anton.letnes at gmail.com paul.anton.letnes at gmail.com
Sun Sep 20 10:04:22 CEST 2015


On Sunday, September 20, 2015 at 9:56:06 AM UTC+2, shiva upreti wrote:
> https://ideone.com/BPflPk
> 
> Please tell me why 'print s' statement is being executed inside loop, though I put it outside.
> Please help. I am new to python.

Hi!

Welcome to python, the most awesome programming language!

The code you pasted used both spaces and tabs for indentation. The thing is that python, by default, interprets one tab character as 8 spaces, but the editor you've used shows it as 4 spaces. To avoid these kinds of headaches, I always 1) set my editor to show tabs, so I can detect them, and 2) never use tabs when I write code myself. I set my editor to insert 4 spaces whenever I hit the "tab" key on my keyboard. If you post the name of your editor, maybe someone knows how to do that in yours. You can also detect mixed space/tab issues by running "python -t" instead of just "python".

So, your "print s" is in fact inside the loop, since the for loop is indented with 4 spaces, and "print s" is indented with 1 tab = 8 spaces. It just doesn't look like that to you.

It looks like you're coding in python 2. If you're new to python, I'd recommend using a python 3 version, maybe 3.4 or 3.5. You can easily pick up python 2 later if you need to maintain old code. Of course, it's not a big deal learning python 3 if you know python 2 either, but why spend energy on it?

Cheers
Paul


More information about the Python-list mailing list