有没有什么方法可以使这个代码更简短,也就是说通过使用某种for循环?

2024-09-30 04:40:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我这样做的目的是,如果用户输入“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"

Tags: 用户目的forgreenbluered绿色elif
1条回答
网友
1楼 · 发布于 2024-09-30 04:40:18

你可以用字典来做这个。想法如下:

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

希望这有帮助!你知道吗

相关问题 更多 >

    热门问题