Python Input validation - positive float or int ac

2019-03-02 10:28发布

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! It accepts int as valid, but why doesn't entry like 1.1 pass? (seemingly a positive numeric entry) We want entry of positive 1 and 1.1 to pass. is there an easy way without two separate blocks, including try/catch?

bookPrice = input("What is the cost of your book? >> ")
while bookPrice.isnumeric() is False or float(bookPrice) < 0:
    bookPrice = input("Use whole # or decimal, no spaces: >> ")
bookPrice = float(bookPrice)
print("Your book price is ${0:<.2f}.".format(bookPrice))

1条回答
虎瘦雄心在
2楼-- · 2019-03-02 10:43

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
查看更多
登录 后发表回答