Screen Link: https://app.dataquest.io/m/350/guided-project%3A-profitable-app-profiles-for-the-app-store-and-google-play-markets/6/removing-non-english-apps-part-one
My Code:
def characters(string):
for character in string:
if ord(character) > 127:
return False
else:
return True
print(characters('Instagram'))
print(characters('爱奇艺PPS -《欢乐颂2》电视剧热播'))
print(characters('Docs To Go™ Free Office Suite'))
print(characters('Instachat 😜'))
What I expected to happen: based on the solutions, I should be getting False for both “print(characters(‘Docs To Go™ Free Office Suite’))” and “print(characters(‘Instachat
’))”.
What actually happened: I get True twice. I can’t see anything wrong with the code, so I am wondering if I am missing something or if there is a reason why ™ and
are being ignored?
True
False
True
True
Thanks for your help!
Hi @2012schmidt.l,
You don’t have to use else
in this case, and it’s important to put return True
outside of the for-loop. Otherwise, the resulting output True
will be related to the last checked character in your string, and not to the whole string itself.
1 Like
Thank you! So if I understand correctly, the problem was that I included ‘return True’ inside the if loop, whereas it should have been outside of it to return True whenever the characters are ord(character) < 127
I updated the code as follows and it gave me the expected result:
def characters(string):
for character in string:
if ord(character) > 127:
return False
return True
print(characters('Instagram'))
print(characters('爱奇艺PPS -《欢乐颂2》电视剧热播'))
print(characters('Docs To Go™ Free Office Suite'))
print(characters('Instachat 😜'))
Result:
True
False
False
False
@Elena_Kosourova, I’ve got one final question. You said that if ‘return True’ is inside the loop, the output will be related to the last checked character, which means that ‘print(characters(‘Docs To Go™ Free Office Suite’))’ and ‘print(characters(‘Instachat
’))’ should return ‘True’ and ‘False’ , respectively, but it returns ‘True’ on both counts? How does that make sense? Thanks for answering my query!
Hi @2012schmidt.l,
Sorry, my mistake, I wanted to say that it returns the result for the first character of a string, not the last one. And then, as soon as the function encounters the return
statement (as soon as the condition of if
is satisfied, which in your previous version of code will happen anyway at the first character, because you included the else
statement), then the function exits immediately, without checking any other characters. That’s why it’s important to put return True
outside the loop: it will be printed only if no character with ord(character) > 127
will be encountered during the for-loop iterations. If at least one “foreign” character is found, the function will exits immediately, returning False
.
Hope it’s clear now and sorry for the confusion in my previous reply.
1 Like