如何在没有这么多嵌套"if"的情况下简要检查值的组合?

  • 本文关键字:情况下 组合 if 嵌套 python
  • 更新时间 :
  • 英文 :


所以我作为初学者学习Python,我需要帮助知道是否有任何方法我可以压缩或重写它以使其更短。目标是获取两个用户输入,它们都是原色,并输出各自的副色。我还希望输入不区分大小写,输入的顺序也不重要。下面的代码是我的方法

color = str(input("Choose a primary color: ")).lower()
color2 = str(input("Choose another primary color: ")).lower()
if color == "red" and color2 == "red":
print("Red")
elif color == "red" and color2 == "blue" or color2 == "red" and color == "blue":
print("Purple")
elif color == "red" and color2 == "yellow" or color2 == "red" and color == "yellow":
print("Orange")
elif color == "blue" and color2 == "yellow" or color2 == "blue" and color == "yellow":
print("Green")
elif color == "blue" and color2 == "blue":
print("Blue")
elif color == "yellow" and color2 == "yellow":
print("Yellow")
else:
print("Invalid")

也是一个链接:https://www.online-python.com/BCOaf5QA0W

你可以在Python中使用集合。

combination = {color, color2}
if combination == {"red"}:
print("red")
elif combination == {"red", "blue"}:
print("purple")
...

总的来说,一组无序和不包含重复。

最新更新