Python 需要帮忙找出我做错了什么吗
我从x+y=result的一个简单定义开始,然后改变了一切,为添加颜色和获得结果做了定义。我添加了if,elif条件。我所有的答案都印成了紫色,我想不出我做错了什么Python 需要帮忙找出我做错了什么吗,python,Python,我从x+y=result的一个简单定义开始,然后改变了一切,为添加颜色和获得结果做了定义。我添加了if,elif条件。我所有的答案都印成了紫色,我想不出我做错了什么 def Add_colors(color1, color2): result=(color1, color2) if('blue', 'red') or ('red', 'blue'): result="purple" elif("red", "
def Add_colors(color1, color2):
result=(color1, color2)
if('blue', 'red') or ('red', 'blue'):
result="purple"
elif("red", "yellow") or ("yellow", "red"):
result="orange"
elif("yellow", "blue") or ("blue", "yellow"):
result="green"
return result
print(Add_colors("red", "blue"))
print(Add_colors("yellow", "blue"))
print(Add_colors("red", "yellow"))
元组不是条件,非空元组的计算结果总是
True
,尝试运行bool(('blue','red')或('red','blue'))
,bool((1,2,3))
和bool(())
,自己测试它
要修复代码
def Add_colors(color1, color2):
result = set((color1, color2))
if result == set(('red', 'blue')):
result="purple"
elif result == set(("red", "yellow")):
result="orange"
elif result == set(("yellow", "blue")):
result="green"
return result
print(Add_colors("red", "blue"))
print(Add_colors("yellow", "blue"))
print(Add_colors("red", "yellow"))
非空元组的计算结果始终为True,如果不进行比较,则这些元组本身将被解释为条件(:-O)如果不与参数的值进行比较,则需要如下尝试:
def Add_colors(color1, color2):
result=(color1, color2)
if result in [('blue', 'red'), ('red', 'blue')]:
result="purple"
elif result in [("red", "yellow"),("yellow", "red")]:
result="orange"
elif result in [("yellow", "blue"),("blue", "yellow")]:
result="green"
return result
因为你的逻辑就到此为止了
if('blue', 'red') or ('red', 'blue'):
这总是真的。所以结果是“紫色”
您可以像上面发布的@Burning Alcohol一样进行修复。第一个if语句对两个元组进行隐式布尔计算,由于非空集合是“truthy”,因此计算结果为True。使用此方法,您只需使用:if result==set(('red','blue'):是否必须使用或之后的值,并在oposite中键入类似(red,blue)或(red,blue)的颜色(蓝色、红色),或者当您使用set时,颜色的顺序根本不重要,它将运行regardles?如果您使用
set
,则set
中元素的顺序相对而言并不重要。如果您有两个以上的元素,则使用set
实际上更好,因为它使代码更干净,处理时间更快。