-1

Having trouble figuring out why these loops don't work as expected. I want the user to be entering a string (height) and if it contains characters, request a height again until certain integers are typed.

First loop: Here. I'm expecting that if I put in a number from 1 until 8, the loop will break, but it doesn't! It keeps requesting the height.

height = input("What's the height?\n")
while type(height) != int or (height < 1 or height >= 9):
    height = input("What's the height?\n")

Second loop: Expecting the same. Loop doesn't break, keeps asking for height.

while True:
    height = input("What's the height?\n")
    if type(height) == int and (height >= 1 and height <= 8):
        break 

Just got into Python but this doesn't seem to be a Python problem, more like something that I'm missing on while loops.

EDIT

Made it work finally. This worked like a charm.

while True:
height = input("What's the height?\n")
if not(height.isalpha()):
    if not(height.isspace()):
        if height != "":
            height = int(height)
            if height >= 1 and height <= 8:
                break 
Gio
  • 11
  • 3

1 Answers1

0

This will address your query:

height = input("What's the height?\n")
while not(height.isnumeric()) or (int(height) < 1 or int(height) >= 9):
    height = input("What's the height?\n")
Srivatsav Raghu
  • 399
  • 4
  • 11