Considering taking a hammer to the computer...

Chris Angelico rosuav at gmail.com
Tue Jan 1 01:08:17 CET 2013


On Tue, Jan 1, 2013 at 10:42 AM,  <worldsbiggestsabresfan at gmail.com> wrote:
> while number_of_floors > 1:
>     floor_number = floor_number + 1
>     print()
>     print ("For floor #",floor_number)
>     rooms_on_floor = int(input("How many rooms are on the floor ?: " ))
>     while rooms_on_floor < 10:
>         print ("Invalid input!")
>         rooms_on_floor = int(input("Enter the number of rooms on floor: "))

You have a loop here that can never terminate, because
number_of_floors never changes.

There are a couple of solutions to this. One would be to compare
floor_number to number_of_floors, and stop the loop once the one
exceeds the other; another (and more Pythonic) way would be to use a
'for' loop, and iterate over the range of numbers from 1 to the number
of floors. See if your son has learned about range(), if so he should
be able to figure it out from that clue.

One tip: When you're asking a question like this, mention what Python
version you're using. I'm guessing it's Python 3.something, but that
might not be right. If it is indeed Python 3, then the repeated
question here will be a problem:

number_of_floors = int(input("How many floors are in the hotel?: "))
while number_of_floors < 1:
    print ("Invalid input!")
    number_of_floors = input("Enter the number of floors in the hotel: ")

Note the difference between the two request lines (other than the
prompt, which is insignificant). The second time around, you're not
turning it into an integer, so that will crash (in Python 3) with the
error that strings and integers aren't ordered (that is, that it makes
no sense to ask whether a string is less than the integer 1). Python
2, on the other hand, will behave very differently here, as input()
has a quite different meaning (and one that you almost certainly do
NOT want).

Chris Angelico



More information about the Python-list mailing list