首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >while循环中的回溯(python 3.x)

while循环中的回溯(python 3.x)
EN

Stack Overflow用户
提问于 2018-01-12 02:16:57
回答 5查看 270关注 0票数 2

我是Python的新手。我想知道我是否可以使用输入并问一个类似“你确定吗?”这样的问题,如果答案是否定的,则返回到原始输入。到目前为止,我得到了这样的结论:

代码语言:javascript
复制
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

我想问一下,在他们输入了他们的选择之后,你确定你的选择吗?如果他们说是,那很好,继续,但如果他们说‘不’,我希望能够转到相同的输入,而不是再次键入整个内容。有没有办法做到这一点?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-01-12 02:23:32

你可以将你想要重复的部分嵌入到你想要突破的while True块中吗?例如:

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2018-01-12 02:22:16

将您已有的代码包装在另一个while循环中:

代码语言:javascript
复制
# 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
票数 1
EN

Stack Overflow用户

发布于 2018-01-12 02:23:16

像这样的东西将会工作(尽管它现在不是最干净的东西)。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48213509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档