Python输入验证-接受正浮点或整数

时间:2018-06-28 15:15:34

标签: python validation input

似乎我们提出了很多要求,但我们正在寻求对输入的正整数或浮点数进行简短验证。下面的代码拒绝否定,文本和空条目-是的!它接受int为有效,但是为什么不通过1.1这样的输入呢? (看似正数输入)我们希望正1和1.1的输入通过。没有两个单独的块(包括try / catch),有没有简单的方法?

$ openstack
Exception raised: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject". See: https://bugzilla.gnome.org/show_bug.cgi?id=709183

1 个答案:

答案 0 :(得分:1)

isnumeric()正在检查所有字符是否都是数字(例如1、2、100 ...)。

如果您输入“。”在输入中,它既不算作数字字符,也不算作'-',因此它返回False

我要做的是尝试将输入转换为 float ,并解决输入错误的问题。 您本可以使用isinstance(),但是为此您需要将输入转换为 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
相关问题