python多次输入数据_Python:如何在输入错误之前重复最后输入提示?

这篇博客讨论了一个编程问题,即在for循环中,如何在用户输入超出预设范围时重新提示输入,而不是跳过错误的值。解决方案是使用while循环和try-except结构来确保用户输入的有效性,直到输入正确为止。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

I have an for statement which prompts the user to input 5. numbers. Like this:

"Input 1. number:

input 2. number:

..

..

.."

I want to repeat the last prompt the user gets before he makes a wrong input (number too big).

But my program skips the wrong one:

like this

"Input 1. number:

5

Accepted

input 2. number:

999

Wrong! Retry

(here I use *continue* for the loop)

input 3.number:

---"

What should I do to re-ask the second question?

解决方案

By using continue you are probably continuing ahead to the next input number. Try something like this:

number_of_inputs = 10

max_input = 99

for i in range(number_of_inputs):

answer = 0

while not answer or answer > max_input:

try:

answer = int(raw_input('Input {}. number: '.format(i)))

except ValueError:

continue

print 'The user selected', answer, 'for input', i

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值