Python 如果没有选项有效,如何回到第一个 if 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12828771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:57:00  来源:igfitidea点击:

How to go back to first if statement if no choices are valid

pythonif-statementraw-input

提问by wondergoat77

How can I have Python move to the top of an if statement if no condition is satisfied correctly.

如果没有正确满足条件,如何让 Python 移动到 if 语句的顶部。

I have a basic if/else statement like this:

我有一个基本的 if/else 语句,如下所示:

print "pick a number, 1 or 2"
a = int(raw_input("> ")

if a == 1:
    print "this"
if a == 2:
    print "that"
else:
   print "you have made an invalid choice, try again."

What I want is to prompt the user to make another choice for this if statement without them having to restart the entire program, but am very new to Python and am having trouble finding the answer online anywhere.

我想要的是提示用户为此 if 语句做出另一个选择,而不必重新启动整个程序,但是我对 Python 非常陌生,并且无法在任何地方在线找到答案。

采纳答案by Andrew Clark

A fairly common way to do this is to use a while Trueloop that will run indefinitely, with breakstatements to exit the loop when the input is valid:

一个相当常见的方法是使用一个while True无限期运行break的循环,当输入有效时,使用语句退出循环:

print "pick a number, 1 or 2"
while True:
    a = int(raw_input("> ")
    if a == 1:
        print "this"
        break
    if a == 2:
        print "that"
        break
    print "you have made an invalid choice, try again."

There is also a nice way here to restrict the number of retries, for example:

这里还有一个很好的方法来限制重试次数,例如:

print "pick a number, 1 or 2"
for retry in range(5):
    a = int(raw_input("> ")
    if a == 1:
        print "this"
        break
    if a == 2:
        print "that"
        break
    print "you have made an invalid choice, try again."
else:
    print "you keep making invalid choices, exiting."
    sys.exit(1)

回答by Jordan Kaye

Use a while loop.

使用while循环。

print "pick a number, 1 or 2"
a = None
while a not in (1, 2):

    a = int(raw_input("> "))

    if a == 1:
        print "this"
    if a == 2:
        print "that"
    else:
        print "you have made an invalid choice, try again."

回答by Abhishek Bhatia

You can use a recursive function

您可以使用递归函数

def chk_number(retry)
    if retry==1
        print "you have made an invalid choice, try again."
    a=int(raw_input("> "))
    if a == 1:
        return "this"
    if a == 2:
        return "that"
    else:
        return chk_number(1)

print "Pick a number, 1 or 2"
print chk_number(0)