gpt4 book ai didi

python - For 循环中的 if 语句 - 逻辑错误

转载 作者:太空宇宙 更新时间:2023-11-03 20:26:46 24 4
gpt4 key购买 nike

有人可以帮我弄清楚为什么此代码对于“Instachat :stuck_out_tongue_winking_eye:”和“Docs To Go™ Free Office Suite”没有返回 False 吗?它们包含 unicode 大于 127 的字符(分别为 emoji 和 TM),因此从技术上讲,它应该为它们返回 False。

我不明白为什么 else 子句在这里不起作用。

# My Code (logic doesn't seem to work)

def is_english(string):

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

else:
return True

print(is_english(‘Instagram’))

print(is_english(‘爱奇艺PPS -《欢乐颂2》电视剧热播’))

print(is_english(‘Docs To Go™ Free Office Suite’))

print(is_english(‘Instachat :stuck_out_tongue_winking_eye:’))

#Solution Code (works but I don't understand why)

def is_english(string):

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

return True

以下应该是“我的代码”的预期输出:真的错误的错误的错误

但是,实际输出是:真的错误的真的正确

最佳答案

因为您需要更改字母代码范围(例如,如下所示):

def is_english(s):
for c in s.lower():
if ord('a') > ord(c) or ord(c) > ord('z'):
return False

return True

关于python - For 循环中的 if 语句 - 逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com