简体   繁体   English

带有 or 的 Python 2.7 if / elif 语句

[英]Python 2.7 if / elif statement with or

i'm fairly new to python so i'm sure i'm doing something wrong.我是 python 的新手,所以我确定我做错了什么。 i am defining a function which accepts a string variable.我正在定义一个接受字符串变量的函数。 i can not be sure exactly what the variable will be, but there a are a 3 values i want to test for and just return a string if are values are found.我不能确定变量到底是什么,但是有 3 个值我想测试,如果找到值就返回一个字符串。 if those values are not found, i simply want to return 'unknown'.如果找不到这些值,我只想返回“未知”。 here is my code:这是我的代码:

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

so then i try to execute:那么我尝试执行:

>> item_priority('orange')

python returns:蟒蛇返回:

'low'

the result i expected to see would be 'unknown'.我希望看到的结果是“未知”。 even if i test with "item_priority('red')", it still returns 'low'.即使我用“item_priority('red')”进行测试,它仍然返回“low”。 the only explanations i have found on this site so far involve code that is more complex than mine.到目前为止,我在这个网站上找到的唯一解释涉及比我的更复杂的代码。

i have tried interchanging the second 'if' with 'elif' but my result is still the same.我尝试将第二个“if”与“elif”互换,但我的结果仍然相同。 i'm not sure what i'm doing wrong here.我不确定我在这里做错了什么。 any help is greatly appreciated.任何帮助是极大的赞赏。 thanks!谢谢!

'yellow' is always evaluating to True within the if-conditional, therefore that block of code is always being executed with whatever you pass in. You need to add or cell_color == 'yellow' to line 2 'yellow'在 if 条件中总是评估为True ,因此无论您传入什么,该代码块总是被执行。您需要添加or cell_color == 'yellow'到第 2 行

The problem is with the line if cell_color == 'green' or 'yellow': .问题在于if cell_color == 'green' or 'yellow':行。 You meant to evaluate if the color is either green or yellow but that is not how or works here您打算评估颜色是green还是yellow ,但这不是这里的工作方式or工作方式

Simply speaking, When you have LEFT or RIGHT like code in python, the LEFT and RIGHT expressions are evaluated first.简单地说,当你在 python 中有类似LEFT or RIGHT的代码时,首先评估LEFTRIGHT表达式。 In your case, this is what happens在你的情况下,这就是发生的事情

  1. LEFT is cell_color == 'green and RIGHT is yellow LEFTcell_color == 'greenRIGHTyellow
  2. When you pass "red" as the color, LEFT evaluates to false当您将"red"作为颜色传递时, LEFT的计算结果为false
  3. Since the LEFT expression was False, RIGHT is evaluated由于LEFT表达式为 False,因此评估RIGHT
  4. Having a string as RIGHT expression, it evaluates to True将字符串作为RIGHT表达式,它的计算结果为 True
  5. False or True evaluates to True and hence the if becomes true and "low" is printed False or True的计算结果为True ,因此if变为 true 并打印"low"

Important thing to remember is, when you use a non empty string where a boolean is expected, it evaluates to True要记住的重要一点是,当您在需要布尔值的地方使用非空字符串时,它的计算结果为True

>>> bool("")
False
>>> bool("abc")
True

So the faulty line should become if cell_color == 'green' or cell_color == 'yellow':所以if cell_color == 'green' or cell_color == 'yellow':


EDIT: Seeing your comment on another answer, it seems you want to check against multiple colors.编辑:看到你对另一个答案的评论,你似乎想检查多种颜色。 In that case, you can use the inbuilt any() function which checks if any of the values of the iterable passed into it evaluates to true.在这种情况下,您可以使用内置的any()函数来检查传递给它的可迭代对象的任何值是否计算为真。

def item_priority(cell_color):
    low_colors = ["green", "yellow", "..."]
    if any(cell_color == color for color in low_colors):
        return "low"

Put your values into an array - then test against that:将您的值放入一个数组中 - 然后对其进行测试:

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

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

Or, more in tune with your code:或者,更符合您的代码:

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'

Dictionary approach:字典方法:

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'
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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM