'Prevent error on int(input()) that is a string and prevent negative number input [duplicate]

this is a very simple question which I have forgotten but for the code I have listed, how would I go about ensuring that no error pops up when a string is input, and also how do I return the question again if there a negative number is input.

roomChoice = int(input("Which room would you like to book?: "))

Hoping to get a response that is clear and concise as I have to explain this in documentation.



Solution 1:[1]

You can use try and except:

while True:
    try: # the block of code below 'try' is being tested
        roomChoice = int(input("Which room would you like to book?: "))
        if isinstance(roomChoice, int) and roomChoice >= 0:  # if roomChoice is an positive int exit the loop
            break
    except ValueError as e: # following is what happens if there's a ValueError
        print(f'An {e} error occured! Input an integer!')

Documentation on try and except: w3schools

OR

You can use pyinputplus module:

import pyinputplus as pyip
roomChoice = pyip.inputInt(prompt="Which room would you like to book?: ", min=0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1