0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
bradmate
  • 41
  • 1

1 Answers1

0

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)
Mszak
  • 186
  • 1
  • 10