Guided project 1 (Python Fundamentals): Question about the is.english() function to check if an app name has english characters

Hello people,

so we have to "write a function that takes in a string and returns False if there’s any character in the string that doesn’t belong to the set of common English characters, otherwise it returns True". After making the function we have to check it on one of the app names called ‘Docs To Go™ Free Office Suite’. The solution code provided by Dataquest returns False for the app. However, when I made the function myself it returns true. I did not change much from the solution just a little edit. But can someone explain to me why I am not getting the same answer as Dataquest?

DATAQUEST SOLUTION CODE:

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

MY CODE:

def english (str):
    for char in str:
        str_index = ord(char)
        if str_index > 127:
            output = False
        elif str_index <= 127:
            output = True
        
    return output 

Thank you :slight_smile:

This is giving me a strong sense of deja vu! I seem to recall having a very similar discussion with another community member about this exact function!

Anyways, what you need to keep in mind here is this - a function halts its execution as soon as it runs into a return clause.

What DataQuest’s code does is this:

  1. It iterates over each character in that string,
  2. If any character’s ord value is greater than 127, False is returned right away and the function ends,
  3. If no character’s ord value was greater than 127, True is returned and the function ends.

DataQuest’s inclusion of the return False clause within the body of the for loop made it sensitive to detecting if the ord value of the thing currently being iterated over was more than 127!

What your code does is this:

  1. Iterates over each character in that string,
  2. Assigns the boolean values of True or False to the output variable based on the ord value of the character currently being iterated over,
  3. As the for loop continues, iterations over additional characters simply over-write the previous boolean value stored in output,
  4. When you return output after the end of the for loop, you’re simply returning info on whether the last character in the string had an ord above 127 or not.

Wow!!! makes so much sense!!! genius haha!!! Sorry i am new to coding so each such kind of explanation blows me away. Thank you very much for your time and quick reply :smiley:
Now I can sleep peacefully :rofl:

1 Like