简体   繁体   English

如何让我的 while 循环返回到 function 的开头?

[英]How do I get my while loop to return to the beginning of the function?

I am making a choice-based game in repl.it, and am allowing the player to choose the color of their turtle.我正在 repl.it 中制作基于选择的游戏,并允许玩家选择他们乌龟的颜色。 Ideally my function asks them for a color, and checks to see if its correct.理想情况下,我的 function 向他们询问颜色,并检查它是否正确。 if the color they pick doesn't match, it gives an error message and is supposed to return to the beginning of the function to ask them again.如果他们选择的颜色不匹配,它会给出一条错误消息,并且应该返回到 function 的开头再次询问他们。 It works when I put in the wrong color, but when I put in a valid answer I am stuck on a never-ending loop of "invalid color selection".当我输入错误的颜色时它会起作用,但是当我输入一个有效的答案时,我会陷入“无效颜色选择”的永无止境的循环。 I've tried using only if statements, returns, and landed upon the while loop and I have been trying to get it to work.我试过只使用 if 语句、返回和登陆 while 循环,我一直在努力让它工作。 I am new to coding.我是编码新手。 Any help would be appreciated, thanks!任何帮助将不胜感激,谢谢!

def rajColorPick():
  NotSelected = True;
  rajColor = str(input("What color would you like raj to be?"));
  colors = ["purple", "pink", "red", "blue", "green"];
  while NotSelected == True:
    if rajColor == colors:
      NotSelected = False;
      tortuga.color(rajColor); 
    elif rajColor != colors:
      print("Invalid color selection. Try again");
      rajColorPick();
  


rajColorPick();

Use the in operator to see if the user input is in the list of colors, and return once you have valid input:使用in运算符查看用户输入是否在 colors 列表中,一旦输入有效就return

def rajColorPick():
    while True:
        rajColor = str(input("What color would you like raj to be?"))
        if rajColor in ["purple", "pink", "red", "blue", "green"]:
            tortuga.color(rajColor)
            return
        print("Invalid color selection. Try again")


rajColorPick()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM