有什么方法可以使此代码更短,更简单,即使用某种for循环吗?

时间:2019-12-25 22:11:02

标签: python algorithm

我这样做是为了使用户输入“ g”将其转换为“绿色” ...“ r” =红色..“ c” =青色....等等

是否可以使用某种循环来代替?谢谢

for i in range(3):
    findColours = input("Enter you're colours -Choose from [red, green, blue, orange, magenta, cyan]:")
    if findColours == "r":
        findColours = "red"
    elif findColours =="g":
        findColours = "green"
    elif findColours =="b":
            findColours = "blue"
    elif findColours =="o":
            findColours = "orange"
    elif findColours =="m":
            findColours = "magenta"
    elif findColours =="c":
            findColours = "cyan"

1 个答案:

答案 0 :(得分:4)

您可以为此使用字典。这是想法:

colors = {"r": "red", "g": "green", "b": "blue", "o": "orange", "m": "magenta", "c", "cyan"}

for i in range(3):
   inputColour = input("Enter you're colours -Choose from [red, green, blue, orange, magenta, cyan]:")

   try:
      findColours = colors[inputColor]
   except:
      # handle exceptions here

希望这会有所帮助!