如何检查输入是否为十进制?

2024-04-24 23:38:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想一个输入,以不断要求一个输入,除非输入是一个数字与两个或更少的小数。你知道吗

number = input('please enter a number')  
while number **is not a decimal (insert code)**:  
. . . .number = input('incorrect input,\nplease enter a number')

Tags: numberinputisnotcode数字insertdecimal
3条回答

您可以使用注释中提到的正则表达式:

import re

def hasAtMostTwoDecimalDigits(x):
    return re.match("^\d*.\d{0,2}$", x)

number = input("please enter a number")
while not hasAtMostTwoDecimalDigits(number):
    number = input("incorrect input,\nplease enter a number")

或者使用decimal模块:

from decimal import Decimal

def hasAtMostTwoDecimalDigits(x):
    x = Decimal(x)
    return int(1000*x)==10*int(100*x)

number = input("please enter a number")
while not hasAtMostTwoDecimalDigits(number):
    number = input("incorrect input,\nplease enter a number")

正如Jon Clements在评论中指出的,这可以变得更简单:

def hasAtMostTwoDecimalDigits(x):
    return Decimal(x).as_tuple().exponent >= -2

因为input给了你一个字符串,所以把它当作一个字符串来处理似乎是最简单的

while len(number.partition('.')[2]) <= 2:

但实际上,您应该将其封装到一个函数中,以检查它是否是一个完全有效的数字。只需执行上面的操作就可以让123..这样的东西通过。所以你可以这样做:

def is_valid(num):
    try:
        float(num)
        return len(a.partition('.')[2]) <= 2
    except Exception:
        return False

我们让float(num)处理num是否看起来像有效的浮点。你知道吗

你可以写

if (yourinput%.01 != 0):

换句话说,如果在第二位小数点后有任何东西。。。你知道吗

相关问题 更多 >