我是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我想问一下,在他们输入了他们的选择之后,你确定你的选择吗?如果他们说是,那很好,继续,但如果他们说‘不’,我希望能够转到相同的输入,而不是再次键入整个内容。有没有办法做到这一点?
发布于 2018-01-12 02:23:32
你可以将你想要重复的部分嵌入到你想要突破的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发布于 2018-01-12 02:22:16
将您已有的代码包装在另一个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发布于 2018-01-12 02:23:16
像这样的东西将会工作(尽管它现在不是最干净的东西)。
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 somethinghttps://stackoverflow.com/questions/48213509
复制相似问题