Home > Net >  How can I tersely check for combinations of values without so many nested "if"s? [closed]
How can I tersely check for combinations of values without so many nested "if"s? [closed]

Time:10-07

So I am learing Python as a beginner, and I need help knowing if there is anyway I could condense this or rewrite it to make it shorter. The goal is to take two user inputs which are primary colors, and output the respective secondary color. I also want the inputs to not be case sensitive, and the order of inputs shouldn't matter. The code below is my approach

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

also a link: https://www.online-python.com/BCOaf5QA0W

CodePudding user response:

You can make use of sets in Python.

combination = {color, color2}

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

In general, a set is unordered and contains no duplicates.

  • Related