Python 2.7 try and except ValueError

前端 未结 3 1357
抹茶落季
抹茶落季 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:48

    Instead of calling inputValue recursively, you need to replace raw_input with your own function with validation and retry. Something like this:

    def user_int(msg):
      try:
        return int(raw_input(msg))
      except ValueError:
        return user_int("Entered value is invalid, please try again")
    

提交回复
热议问题