Project 1 - Unexpected output

Screen Link: https://app.dataquest.io/m/428/guided-project%3A-profitable-app-profiles-for-the-app-store-and-google-play-markets/6/removing-non-english-apps-part-one

My Code:

def is_english(string):
    non_ascii = 0
    for character in string:
        if ord(character) > 127:
            return False
        
        if non_ascii >= 3:
            return false
        else:
            return True
        
print(is_english('Docs To Go™ Free Office Suite'))
print(is_english('In欢乐颂2电视剧😜'))

What I expected to happen:
I think the second print should output False.

What actually happened:

Instead it outputted True.

also, can you help me understand why did we pass an argument the “string” to the def is_english, please?

thank you

The reason why it’s outputting True is that your non_ascii variable will always have the value 0.

Inside your function, you are not updating the non_ascii variable at all. So, its value won’t go higher than 3. So, the if condition -

will always be False and as a result, the code part of the else statement will run and you will always get True. You need to see where and how the non_ascii variable would get updated.

That’s the input parameter to your function. I would recommend going through the Functions: Fundamentals - Parameters and Arguments content again to better understand what input parameters are. If there are any questions even after that, let me know!

Great, thank you kind Sir!

What @the_doctor mentioned above about the control logic problem is right, non_ascii seemed to be used as a counter but you didn’t update it.

Rather than saying “always” …, with the implication that a loop is going on, I want to point out that your code doesn’t even loop through the characters and only reads the 1st character in the string before it returns after 1st iteration of loop.

Lesson:
Never return in loop unless you want short-circuiting behaviour (Short Circuiting Techniques in Python - GeeksforGeeks).
Even if you fixed the logic to properly count non_ascii >= 3, it still won’t work because you only allowed the code to check the 1st character in the string. You can’t have >= 3 unless you let it check at least 3 characters. Of course what we want here is actually to check the entire string, unless the lesson is asking for something weird (please paste lesson link too for every question so others know what the question expects)

1 Like