Integers as the only valid inputs

前端 未结 3 616
暗喜
暗喜 2021-01-27 10:22

What I\'m trying to do is ask users for two inputs, if one of the inputs is less than zero or if the input is some string then ask for the inputs again. The only valid input are

相关标签:
3条回答
  • 2021-01-27 10:46

    The solution is to coerce the answer to int() and catch any exceptions, for example:

    while True:
        try:
            number_of_books = int(raw_input('Enter number of books:'))
            if number_of_books < 0:
                raise ValueError('must be greater than zero')
        except ValueError, exc:
            print("ERROR: %s" % str(exc))
            continue
        break
    

    Probably you should put this in a function, and make the prompt a variable (to allow re-use).

    0 讨论(0)
  • 2021-01-27 10:50

    You should use a while loop for each input, so only the invalid one is asked again. By using while True, you ask for input once, and break once it's valid. Try to convert to int, which raises ValueError if that cannot be done. Exceptions cause the custom error to be printed, and the loop restarted.

    while True:
        books_input = input("What is the number of books in the game?: ")
        try:
            number_of_books = int(books_input)
            if number_of_books < 0:
                raise ValueError
        except ValueError:
            print('Input must be an integer and cannot be less than zero')
        else:
            break
    

    You'd need to do this for each input (maybe there are more than two?), so it makes sense to create a function to do the heavy lifting.

    def non_negative_input(message):
        while True:
            input_string = input(message)
            try:
                input_int = int(books_input)
                if input_int < 0:
                    raise ValueError
            except ValueError:
                print('Input must be an integer and cannot be less than zero')
            else:
                break
        return input_int
    

    Calling it:

    non_negative_input("What is the number of books in the game?: ")
    
    0 讨论(0)
  • 2021-01-27 10:58

    Use the try except method

    while stringval = input("What is the number you want to enter"):
      try:
        intval = int(stringval)
        if intval > -1:
          break
      except ValueError:
        print 'Invalid answer, try again'
    
    # Process intval now
    
    0 讨论(0)
提交回复
热议问题