Indentation - finding english apps in the first guided project

Screen Link:

My Code:

    def english(string):
        for character in string:
            if ord(character) > 127:
                return False
            return True

print(english('Instagram'))
print(english('爱奇艺PPS -《欢乐颂2》电视剧热播'))
print(english('Docs To Go™ Free Office Suite'))
print(english('Instachat 😜'))

What I expected to happen:
True
False
False
False

What actually happened:

True
False
True
True

The “right” code is below:

    def english(string):
        for character in string:
            if ord(character) > 127:
                return False
        return True

So the only difference is that the indentation of “return True” in the end. I can understand that the “right” code is right because “return True” should be included in for loop, but why does it still work even if it’s included in the if code? Thanks!

1 Like

I guess you are interpretation of indentation is wrong

In first block of code return True is part of for loop not if loop.


and in second code

return True is part of function body not for loop.


More you can try Python-tutor to understand what is happening line-by-line

For First block

For second code

2 Likes

WOWWWOWOW Thank you, this was such a basic thing which i havent been through thoroughly. thank you!

1 Like