Python 2.7 try and except ValueError

前端 未结 3 1356
抹茶落季
抹茶落季 2021-02-07 07:33

I query user input which is expected to be an int by using int(raw_input(...))

However when the user doesn\'t enter an integer, i.e. just hits return, I get a ValueError

3条回答
  •  情歌与酒
    2021-02-07 07:59

    A quick and dirty solution is:

    parsed = False
    while not parsed:
        try:
            x = int(raw_input('Enter the value:'))
            parsed = True # we only get here if the previous line didn't throw an exception
        except ValueError:
            print 'Invalid value!'
    

    This will keep prompting the user for input until parsed is True which will only happen if there was no exception.

提交回复
热议问题