如果没有选择有效,如何返回第一个if语句 [英] How to go back to first if statement if no choices are valid

查看:362
本文介绍了如果没有选择有效,如何返回第一个if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I have a basic if/else statement like this:

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很新,并且无法在任何地方在线找到答案。

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.

推荐答案

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

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

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)

这篇关于如果没有选择有效,如何返回第一个if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆