Python-使用while循环重复代码 [英] Python - Repeating code with a while loop

查看:414
本文介绍了Python-使用while循环重复代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题.我有一大堆输入代码,以防输入错误.到目前为止,这就是我所拥有的(请注意,这只是一个示例代码,我在打印和输入中拥有的实际值是不同的:

So here is my question. I have a chunk of input code that I need to repeat in case the input is wrong. So far this is what I have (note that this is just an example code, the actual values I have in print and input are different:

input_var_1 = input("select input (1, 2 or 3)")
if input_var_1 == ("1"):
    print ("you selected 1")
elif input_var_1 == ("2")
    print ("you selected 2")
elif input_var_1 == ("3")
    print (you selected 3")
else:
    print ("please choose valid option")

我要在ELSE之后添加什么,以便第一个IF和最后一个ELIF之间的所有代码都重复执行,直到输入有效为止?我现在所得到的只是简单地重复执行3次代码,但是问题在于它只重复输入请求3次,而且太大而且不切实际.

What do I add after the ELSE so that all the code between the first IF and last ELIF gets repeated until the input is valid? What I have now is just plain repeat of the code 3 times, but the problem with that is that it repeats the input request only 3 times and that it's too large and impractical.

谢谢您的协助!

推荐答案

umutto 所述,您可以使用while循环.但是,不是在每个有效输入上使用break,而是可以在结尾处有一个中断,使用continue跳过不正确的输入即可保留在循环中.如下

As alluded by umutto, you can use a while loop. However, instead of using a break for each valid input, you can have one break at the end, which you skip on incorrect input using continue to remain in the loop. As follows

while True:
    input_var_1 = input("select input (1, 2 or 3): ")
    if input_var_1 == ("1"):
        print ("you selected 1")
    elif input_var_1 == ("2"):
        print ("you selected 2")
    elif input_var_1 == ("3"):
        print ("you selected 3")
    else:
        print ("please choose valid option")
        continue
    break

我还清理了您代码中的其他一些语法错误.经过测试.

I also cleaned up a few other syntax errors in your code. This is tested.

这篇关于Python-使用while循环重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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