Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

python - 如何修复验证有效响应的循环?(How do I fix my loop for verifying a valid response?)

when i run this code, and i input an invalid response, it works perfectly fine by asking me to input a valid response.

(当我运行此代码,并且输入无效的响应时,要求我输入有效的响应就可以很好地工作。)

But when i input an invalid response and it asks me to input again and I input a valid response, it doesn't break the loop.

(但是,当我输入无效的响应并且要求我再次输入并且输入有效的响应时,它不会中断循环。)

How do I fix this?

(我该如何解决?)

def plchoice():
    global choice
    global plchoice
    plchoice = input("Rock, Paper, Or Scissors: ")
    while plchoice not in ["rock", "Rock", "Paper", "paper", "Scissors", "scissors"]:
        print("Invalid Choice! Pick Again.")
        choice = input("Rock, Paper, Or Scissors: ")
  ask by PythonBeginner69 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It doesn't break out of the loop because you never change the value of plchoice , you are setting the value of choice in the loop.

(它不会中断循环,因为您永远不会更改plchoice的值, plchoice在循环中设置choice值。)

Also, using global variables is not pythonic.

(另外,使用全局变量不是pythonic。)

Consider having the game_over() function have the arguments (plchoice,cpchoice) .

(考虑让game_over()函数具有参数(plchoice,cpchoice) 。)

If you edit the plchoice and cpchoice functions to return their values rather than setting the globabl value, you can then change the game_going() function to:

(如果您编辑plchoice和cpchoice函数以返回其值而不是设置globabl值,则可以将game_going()函数更改为:)

def game_going():
    game_over(plchoice(),cpchoice())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...