Python Input validation - positive float or int accepted

前端 未结 1 554
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 00:27

seems we are asking a lot, but we are seeking a short validation for positive int or float being entered as input. The code below rejects negative, text and null entries - yay!

1条回答
  •  遥遥无期
    2021-01-24 00:53

    isnumeric() is checking if all the characters are numeric (eg 1, 2, 100...).

    If you put a '.' in the input, it doesn't count as a numeric character, nor does '-', so it returns False.

    What I would do is try to convert the input to float, and work around bad inputs. You could've used isinstance(), but for that you would need to convert the input to something else than string.

    I came up with this:

    message = "What is the cost of your book? >>"
    while True:
        bookPrice = input(message)
        try:
            bookPrice = float(bookPrice)
    
            if bookPrice  <= 0:
                message = "Use whole # or decimal, no spaces: >> "
                continue
            currect_user_input = True
    
        except ValueError:
            currect_user_input = False
            message = "Use whole # or decimal, no spaces: >> "
    
        if currect_user_input:
            print("Your book price is ${0:<.2f}.".format(bookPrice))
            break
    

    0 讨论(0)
提交回复
热议问题