Python - Repeating code with a while loop

老子叫甜甜 提交于 2019-12-04 05:51:15

问题


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? 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.

Thank you for your assistance!


回答1:


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.




回答2:


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.




回答3:


Like mani's solution, except the use of continue was redundant in this case.

Also, here I allow int() float() or string() input which are normalized to 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")


来源:https://stackoverflow.com/questions/43268186/python-repeating-code-with-a-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!