Python 2.7 if / elif语句带或

问题描述 投票:0回答:3

我对python很新,所以我确定我做错了什么。我正在定义一个接受字符串变量的函数。我不能确定变量究竟是什么,但是我想要测试的是3个值,如果找到值则只返回一个字符串。如果找不到这些值,我只想返回'未知'。这是我的代码:

def item_priority(cell_color):
  if cell_color == 'green' or 'yellow':
    return 'low'
  elif cell_color == 'red':
    return 'high'
  else:
    return 'unknown'

所以然后我尝试执行:

>> item_priority('orange')

python返回:

'low'

我预计看到的结果将是“未知”。即使我用“item_priority('red')”进行测试,它仍然会返回'低'。到目前为止,我在这个网站上找到的唯一解释涉及的代码比我的更复杂。

我尝试将第二个'if'与'elif'交换,但我的结果仍然相同。我不确定我在这里做错了什么。任何帮助是极大的赞赏。谢谢!

python if-statement boolean-logic
3个回答
0
投票

'yellow'总是在if条件中对True进行评估,因此该代码块始终与您传入的任何内容一起执行。您需要将or cell_color == 'yellow'添加到第2行


0
投票

将您的值放入数组 - 然后测试:

validColors = ["red", "black", "blue", "yellow"]
color = "red"

if color in validColors:
    print("Found it")
else:
    print("Not found")

或者,更符合您的代码:

def item_priority(cell_color):
  lowColors = ["green", "yellow"]
  highColors = ["red"]

  if cell_color in lowColors:
    return 'low'
  elif cell_color in highColors:
    return 'high'
  else:
    return 'unknown'

字典方法:

def item_priority(cell_color):
  colors = {}
  colors["high"] = ["red"]
  colors["low"] = ["green", "yellow"]

  if cell_color in colors["low"]:
    return 'low'
  elif cell_color in colors["high"]:
    return 'high'
  else:
    return 'unknown'

0
投票
def item_priority(cell_color):
    if cell_color == 'green' or cell_color == 'yellow' :
        return 'low'
    elif cell_color == 'red' :
        return 'high'
    else:
        return 'unknown'
item_priority('Orange')
© www.soinside.com 2019 - 2024. All rights reserved.