需要帮助弄清楚我做错了什么

时间:2020-11-10 03:49:57

标签: python

i从x + y = result的简单def开始,然后更改了所有内容以定义添加颜色并获得结果的定义。我添加了ifif条件。我所有的答案都是紫色,我无法弄清楚自己做错了什么。

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

3 个答案:

答案 0 :(得分:0)

元组不是条件,非空元组的总评估值为True,请尝试运行bool(('blue', 'red') or ('red', 'blue'))bool((1,2,3))bool(())自己进行测试,< / p>

修复您的代码,

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

答案 1 :(得分:0)

因为你的逻辑就停在这里

if('blue', 'red') or ('red', 'blue'):

总是如此。所以结果是“紫色” 您可以像上面发布的@Burning Alcohol一样进行修复。

答案 2 :(得分:-1)

非空元组的值始终为True,如果不进行比较,则它们本身将被解释为条件(:-O)。如果不与参数值进行比较,则需要这样尝试:< / p>

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
相关问题