Looking for clarity on logic of for loops on [Guided project : profilable app]

Hi,

I’m on 7th mission Removing Non-English Apps on Guided Project: Profitable App Profiles for the App Store and Google Play Markets.

When i try to create the function to check whether these app names are detected as English or non-English, i’m facing an issue of the logic of the code.

What is the different of logique between the 2 codes of for Loops below please ?

  1. On the first code, the line**“return True”** is indente on if clause
  2. On the second code, the line “return True” is indent on For Loops.

but when i run then first code, he make the loop juste for the first character and not for all.
can you explain me the logic and why he don’t loop for all the String please?

Screen Link:

My Code:

def is_english(a_name):
    for val in a_name:
        if ord(val)>127:
            return False
        return True
        
print(is_english('Instagram'))

print(is_english('爱奇艺PPS -《欢乐颂2》电视剧热播'))

print(is_english('Docs To Go™ Free Office Suite'))

print(is_english('Instachat 😜'))

What I expected to happen on the result:

True
False
False
False
False

What actually happened:

True
False
True
True
True

solution Code:

def is_english(a_name):
    for val in a_name:
        if ord(val)>127:
            return False
    return True
for val in a_name:
    if ord(val) > 127:
         return False
   else:
         return True

is the same as

for val in a_name:
    if ord(val) > 127:
         return False
    return True

is also same as

if ord(a_name[0]) > 127:
    return False
else:
    return True

is also the same as

if ord(a_name[0]) > 127:
    return False

return True

is also the same as

return not (ord(a_name[0]) > 127)

The function checks only one value. And, return True if the first word is English; otherwise, return False.

What we want the function to do is to check for all values.

Put the return True the statement outside of for loop.

for val in a_name:
    if ord(val) > 127:
         return False

return True

This works because any invalid (non-English) word is caught within the for loop and function return immediately with False.

Once the for loop completes checking all the words in the a_name, we know all words are English words. At end, the function return True.

Thank you for the response, it really help me :slight_smile:

1 Like