Python输入验证-接受正浮点或整数 [英] Python Input validation - positive float or int accepted
问题描述
似乎我们提出了很多要求,但是我们正在寻求对输入的正整数或浮点数进行简短验证.下面的代码拒绝否定,文本和空条目-是的!它接受int为有效,但是为什么不通过1.1这样的输入呢? (看似正数输入)我们希望正1和1.1的输入通过.没有两个单独的块(包括try/catch),有没有简单的方法?
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()
正在检查所有字符是否都是数字(例如1、2、100 ...).
isnumeric()
is checking if all the characters are numeric (eg 1, 2, 100...).
如果您输入."在输入中,它既不算作数字字符,也不算作'-',因此它返回False
.
If you put a '.' in the input, it doesn't count as a numeric character, nor does '-', so it returns False
.
我要做的是尝试将输入转换为 float ,并解决输入错误的问题.
您本可以使用 isinstance()
,但是为此您会需要将输入内容转换为 string 以外的其他内容.
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.
我想到了这个
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
这篇关于Python输入验证-接受正浮点或整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!