11

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

我有一个基本的 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."

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

4

3 回答 3

14

一个相当常见的方法是使用一个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."

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

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)
于 2012-10-10T21:39:01.783 回答
4

使用 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."
于 2012-10-10T21:36:27.197 回答
4

您可以使用递归函数

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)
于 2012-10-10T21:44:18.797 回答