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

标签 python for-loop if-statement logic

有人可以帮我弄清楚为什么此代码对于“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/

相关文章:

python - django:使用 ManyToMany 批量更新对象

python - 操作系统错误: port/proto not found in for loop

python - 使用 django-allauth 无法进行电子邮件身份验证

c - 读取两个整数并找出第一个整数的所有小于第二个整数的正倍数

javascript - 隐藏变量直到需要为止?

jquery - 如何使用Jquery对每个匹配元素重复IF语句

python - pandas sort_index 文档

javascript - JavaScript 中的数组错误 : Uncaught TypeError: Cannot read property 'x' of undefined

C for 循环与 rolled out 循环有不同的效果

java - 如何更改 if 和 for 在测试中断言