python do while循环,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")

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!

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值