0

"I cannot properly implement input validation"

"Attempted Try and Except but to no avail"

#Variables
floors = [];
n = int(input('Enter number of floors of the hotel : '));
totalRooms = 0;
occupiedRooms = 0;
#Input Process
while True:
    for i in range(0, n):
        print ('For floor ' + str(i + 1) + ' : ');
        try:
                rooms = int(input('Enter the number of rooms : '));
                occupied = int(input('Enter the number of rooms occupied : '));
                floors.append([rooms, occupied]);
        except ValueError:
            print("Try again")




    totalRooms = totalRooms + rooms;
    occupiedRooms = occupiedRooms + occupied;

#Display Information
print ('Total Rooms : ' + str(totalRooms));
print ('Total Rooms Occupied: ' + str(occupiedRooms));
print ('Total Rooms Unoccupied: ' + str(totalRooms - occupiedRooms));
print ('Percent of Rooms Occupied: ' + str(((occupiedRooms * 1.0) / (totalRooms * 1.0)) * 100));

I would like to have it so it keeps asking the user until they input a number

Flamonga
  • 37
  • 5

1 Answers1

1

Swap:

n = int(input('Enter number of floors of the hotel : '));

With:

while True:
    try:
        n = int(input('Enter number of floors of the hotel : '));
        if isinstance(n, int):
            break
    except ValueError:
        print("try again")
        continue

Output:

daudnadeem:rubbish daudn$ python3.7 burn.py 
Enter number of floors of the hotel : A
try again
Enter number of floors of the hotel : a
try again
Enter number of floors of the hotel : 22
For floor 1 : 
Enter the number of rooms : 

OR

Simply create a function like below to take inputs:

def ask_input(message):
    try:
        n = int(input(message))
        return n
    except ValueError:
        print("Please enter an integer value")
        return ask_input(message)

Now, whenever you need an input, you can use something like below:

n = ask_input('Enter number of floors of the hotel : ')

You can reuse the function for any number of inputs and can change the message.

Community
  • 1
  • 1
DUDANF
  • 2,618
  • 1
  • 12
  • 42