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))
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: