Integers as the only valid inputs

前端 未结 3 614
暗喜
暗喜 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: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?: ")
    

提交回复
热议问题