Home > Mobile >  why does it pop an error when I already set a rule in while?
why does it pop an error when I already set a rule in while?

Time:04-26

I already set if weight and height isn't an integer, ask to user to input it again. but it pop: "ValueError: invalid literal for int() with base 10" instead". thanks for helping


while type(weight) != int and type(height) != int and weight not in weightrange and height not in heightrange:

        weight = int(input("Enter a weight number please (kg): "))

        height = int(input("Enter a height number please (cm): "))

CodePudding user response:

I'm going to jump in, because I think you're on the wrong track. You must remember that things execute IN ORDER, from top to bottom. You can't "establish a rule" and hope that the rule will be applied in the future. Python just doesn't work that way. Some languages do, Python does not.

while True:
    weight = input("Enter a weight number please (kg): ")
    if weight.isdigit():
        weight = int(weight)
        if weight in weightrange:
            break
        else:
            print( "Weight not in range.")
    else:
        print( "Please enter an integer.")
while True:
    height = input("Enter a height number please (cm): ")
    if height.isdigit():
        height = int(height)
        if height in heightrange:
            break
        else:
            print( "Height not in range.")
    else:
        print( "Please enter an integer.")

If you were doing this for real, you would probably create a function to avoid typing all of that twice.

CodePudding user response:

Simply do this,

while True:
  try:
    weight = int(input("Enter a weight number please (kg): "))
    height = int(input("Enter a height number please (cm): "))
    break
    
  except:
    print("Invalid Input")

You can modify this to fit your height and weight ranges too.

  • Related