The only way you'd get the behaviour you see is if you indented return total
to be part of the for
loop. If it doesn't look like that in your editor, it's because you have used a TAB character for your return
line:
>>> code_as_posted = '''\
... def test(word):
... total = 0
... for l in word:
... print l
... return total
... '''
>>> code_as_posted.splitlines()[-1]
'\treturn total'
See that \t
character escape there? That's a tab character, which expands to up to 8 spaces when interpreted by Python; see Indentation in the Python reference documentation:
First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation.
As the return
exits the loop early, you only ever see the 'p'
character printed.
Both your editor and the Stack Overflow Markdown implementation display tabs as four spaces instead, so it was really hard to spot this specific error here. Run Python with the -tt
command line switch to raise exceptions on mixed tab-and-spaces use.
You need to configure your editor to expand tabs to spaces, or use tabs exclusively. Don't mix the two styles. The Python Style Guide strongly recommends you use spaces only:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Many editors can also make tabs explicitly visible. In Sublime Text, when you select text, spaces are shown as dimmed dots, tabs as a line:
