def string_func(a_string):
for char in a_string:
if ord(char) > 127:
return False
return True
print(string_func('Instagram'))
print(string_func('爱奇艺PPS -《欢乐颂2》电视剧热播'))
print(string_func('Docs To Go™ Free Office Suite'))
print(string_func('Instachat 😜'))
What I expected to happen:
According to the assignment, the last two functions should output ‘False’ because the string contains characters outside the ASCII range (0 - 127). The characters outside the range of ASCII are ‘™’ in ‘Docs To Go™ Free Office Suite’, and ‘’ in ‘Instachat ’.
What actually happened:
I get ‘True’ instead of ‘False’, I can’t figure out why.
Guys, never mind! Let me explain what I did wrong in case somebody in the future encounters the same issue.
It was a dumb mistake.
My code was:
def string_func(a_string):
for char in a_string:
if ord(char) > 127:
return False
return True # <--- this line was the issue; I made an indentation error :(
return True #<--- this line is correct, now it's returning False, as expected!
print(string_func('Instagram'))
print(string_func('爱奇艺PPS -《欢乐颂2》电视剧热播'))
print(string_func('Docs To Go™ Free Office Suite'))
print(string_func('Instachat 😜'))
In the first iteration of the for loop when handling “Instagram”, it checks if the ord() of the first character “i” is greater than 127. Since it is False, it jumps to the next line of code within the for loop (as if and the second return has the same indentation and returns True without looping through rest of the characters. So if the indentation is wrong, it only checks the first character only and gives us a wrong output(2 of them turned out to be the right output out of luck.)
When you move the indentation back, after the first False the control goes back to loop again through rest of the characters until it finds a char that has ord() more than 127. When that happens, it will return False, if not, returns True at the end of all iterations.
thank you for the explanation, but i’m still confused. the fact that the second return (return True) has the same indent as “for char in a_string:” is throwing me off. how does Python know to run "if ord(char) > 127: when the indents don’t align?