-1

I am writing python script that need to provide multiple input (my case more than 20).

I am terminating program whenever they provided wrong inputs due to this users facing some difficulties say for example they provided all 19 correct inputs and the last input provided wrongly by mistake and program gets terminated and they end up by re run the script and provide all 20 inputs again.

Below is my code:

print('1)INT\n2)US\n3)UK\n4)China')
geo = raw_input('Please choose the Geography:')
while geo != '1' and geo != '2' and geo != '3' and geo != '4':
    print('Error: Provide proper input and tool terminated. Please re Run the tool ')
quit()

Instead of this I need to give three chances and if they failed to 3 times then I need terminate the program.

Please advice.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
asteroid4u
  • 79
  • 2
  • 9
  • 3
    Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – idjaw Mar 26 '17 at 13:34
  • Use a variable as a counter to accumulate number of wrong inputs and add a condition based on that variable to the while statement. – wwii Mar 26 '17 at 15:26

2 Answers2

0

For user input validation, kindly refer to the question mentioned in the comment. Apart from that, some misc. improvements I thought of which may help you -

choices = ['INT', 'US', 'UK', 'China']

print('\n'.join('{}) {}'.format(i+1, choice) for i, choice in enumerate(choices)))

tries = 0
while tries < 3:
    geo = raw_input('Please choose the Geography:')
    if not (geo and geo.isdigit() and 1 <= int(geo) <= len(choices)):
        print('Error: Provide proper input and tool terminated. Please re Run the tool ')
        tries += 1
    else:
        break
Community
  • 1
  • 1
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
0
MAX_RETRY_COUNT = 3
retry_count = 0

print('1)INT\n2)US\n3)UK\n4)China')

while retry_count < MAX_RETRY_COUNT:
    geo = raw_input('Please choose the Geography:')
    if geo in ('1', '2', '3', '4'):
        break
    retry_count += 1
    print('Error: Provide proper input and tool terminated. Please re Run the tool ')

if retry_count == MAX_RETRY_COUNT:
    print('Exit: Max retry error {}'.format(MAX_RETRY_COUNT))

quit()
tell k
  • 605
  • 2
  • 7
  • 18