Python fundamental project- remove non-English app part

Hi I discovered an interesting glitch and I hope you can help me explain it with your expertise:

I wrote a function find if a string is English or not like this:

def IsThisEnglish(str):
     for character in str:
         if ord(character) >127:
            return False
         return True

If I left my return True in the if function, str with emoji and non-standard English text will also return True while it shouldn’t be.

Can you help me explain why?

Your code:

Suppose if we have a non-English character, then if ord(character) >127 condition will be True. And, it will return return False. This behavior is intended as the problem described. That is, so far so good.

Now, suppose if we have a English character, then if ord(character) >127 condition will be False.

And, the python interpreter will read the next line return True. Therefore, for the first English character in the str, it will immediately return True. The placement of return True within the for loop is exactly the problem here since we need to check for all characters in str including the first character.

To fix the problem, we can place return True outside of the for loop.

for character in str: 
    if ord(character) >127: 
          return False 

# outside of the for loop
return True

Another style using break:

for character in str: 
    if ord(character) >127: 
         break
else:
    # Did not break out of the for loop
    # Successfully check all elements are English characters
    return True

# Did break out of the for loop
# There exists at least one element is non-English character
return False
2 Likes

I have modified your post to the following:

  • Remove the quotes >. Easier to read without quotes.
  • Place ``` triple back tick on a single line on its own.
  • Use single ` back tick instead of single quote ’ to highlight code inline.

You can press the edit button to see what I have edited.

1 Like