gpt4 book ai didi

python - if, elif, else 链不能正常工作?

转载 作者:行者123 更新时间:2023-11-28 19:40:43 28 4
gpt4 key购买 nike

我正在学习“艰难地学习 Python”,但遇到了障碍。书上给出了一个单元测试,要求你写一个函数来满足测试。但是,当我将此函数导入交互式 shell 进行测试时,任何输入都会返回“方向”,我不明白为什么。

这是我的代码:

def pos(item):
""" Get part of speech for item. """
pos = ''
if item == 'north' or 'south' or 'east':
return 'direction'
elif item == 'go' or 'kill' or 'eat':
return 'verb'
elif item == 'the' or 'in' or 'of':
return 'stop'
elif item == 'bear' or 'princess':
return 'noun'
else:
try:
int(item)
return 'number'
except ValueError:
return 'error'

最佳答案

你应该这样写:

if item == 'north' or item == 'south' or item == 'east':

或者,或者:

if item in ('north', 'south', 'east'):

其余分支也是如此。

要解释您的原始代码失败的原因,请考虑 Python 如何解析以下表达式:

item == 'north' or 'south' or 'east'

Python 的作用如下(注意括号中表示解析的顺序):

(item == 'north') or 'south' or 'east'

这里有三个子表达式。 item == 'north' 很可能是假的(除非你碰巧输入了 'north')。但是,'south''east' 在 bool 上下文(即条件)中计算时始终为 True,因此您结束使用 (item == 'north') 或 True 或 True,这当然是 True

关于python - if, elif, else 链不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463256/

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