简体   繁体   English

Python-使用while循环重复代码

[英]Python - Repeating code with a while loop

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")

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

Thank you for your assistance! 谢谢您的帮助!

As alluded by umutto , you can use a while loop. 正如umutto所暗示的,您可以使用while循环。 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. 但是,您可以在结尾处有一个中断,而不是对每个有效输入都使用break ,您可以使用continue保留在循环中来跳过不正确的输入。 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. 经过测试。

A much effective code will be 一个有效的代码将是

input_values=['1','2','3']
while True:
    input_var_1 = input("select input (1, 2 or 3): ")
    if input_var_1 in input_values:
        print ("your selected input is "+input_var_1)
        break
    else:
        print ("Choose valid option")
        continue

I suggested this answer because I believe that python is meant to do a job in minimalistic code. 我建议使用此答案,因为我相信python可以用简约的代码完成工作。

Like mani's solution, except the use of continue was redundant in this case. 像mani的解决方案一样,在这种情况下,除了continue的使用是多余的。

Also, here I allow int() float() or string() input which are normalized to int() 另外,在这里我允许将int()的float()或string()的输入标准化为int()

while 1:
    input_var_1 = input("select input (1, 2, or 3): ")
    if input_var_1 in ('1','2','3',1,2,3):
        input_var_1 = int(input_var_1) 
        print 'you selected %s' % input_var_1
        break
    else:
        print ("please choose valid option")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM