Python: How to repeat the last input prompt before wrong input?

北慕城南 提交于 2019-12-23 23:18:28

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13499448/python-how-to-repeat-the-last-input-prompt-before-wrong-input

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