Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indentation in function does not work as expected [duplicate]

I found something that doesn't make sense to me. I am hoping that someone can explain it.

def test(word):
    total = 0
    for l in word:
        print l

test('python')

The result is 'p y t h o n' (each letter appears on its own line).

def test(word):
    total = 0
    for l in word:
        print l
    return total

test('python')

The result is just 'p'.

How come adding a return statement has this effect? Shouldn't both blocks of code do that same thing? Does this mean that it goes through the for loop only once and then executes the return statement?


2 Answers

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:

Sublime Text editor with code from OP selected; the tab on the return line is visible as a line, spaces are shown as subtle grey dots

like image 128
Martijn Pieters Avatar answered Sep 14 '26 19:09

Martijn Pieters


I am 100% sure that return total in the second function is on the same level (indented exactly) as print. Probably you use mixed space characters (tab or space).

like image 45
Dmitry Nedbaylo Avatar answered Sep 14 '26 18:09

Dmitry Nedbaylo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!