[英]Backtracking in a while loop (python 3.x)
我是Python的新手。 我想知道我是否可以使用输入内容并询问“您确定吗?”之类的问题,如果答案是否定的,请返回原始输入内容。 到目前为止,我已经做到了:
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
if variable == "a":
do things
if variable == "b":
do other things
etc etc
我想问一问,他们输入选择后,您确定选择吗? 如果他们说“是”,那就继续吧,但是如果他们说“否”,我希望能够输入相同的内容而不必再次输入整个内容。 有什么办法吗?
你可以嵌入要在重复位while True
,你打出来的块? 例如:
while True
answer = input("What is the correct answer, a, b, or c? ")
check = input("Are you sure (y/n)? ")
if check=="y" or check=="Y":
break
取得已有的代码,然后将其包装在另一个while循环中:
# loop forever until they confirm their choice
while True:
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
confirm = input("You entered %s. Is this correct?" % variable)
if confirm == "yes":
break
这样的事情会起作用(尽管现在还不是最干净的东西)。
def prompt_for_something():
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
confirm = input("Are you sure?")
if confirm == "No": return False
return variable
option = prompt_for_something()
while option == False:
option = prompt_for_something()
if option == "a":
do something
ok=False
while not OK:
variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
variable = input("Make a correct choice. ")
ishesure=input("You chose {}, Are you sure? (Y or N)".format(variable))
if ishesure=="Y":
ok=True
应该管用。 您将所有内容都用while循环包围,该循环将一直循环直到客户在第二个问题中输入“ Y”为止,直到他输入了有效的变量值
具有可编辑的控制台输出并不容易。 如果只适合您,则可以按“向上”箭头键返回到最后输入,但是如果要将其嵌入到代码中,则使用合适的GUI(即tkinter)可能比使用您的代码更容易。是做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.