number = input('please enter a number')
while number **is not a decimal (insert code)**:
. . . .number = input('incorrect input,\nplease enter a number')
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")
您可以使用注释中提到的正则表达式:
或者使用
decimal
模块:正如Jon Clements在评论中指出的,这可以变得更简单:
因为
input
给了你一个字符串,所以把它当作一个字符串来处理似乎是最简单的但实际上,您应该将其封装到一个函数中,以检查它是否是一个完全有效的数字。只需执行上面的操作就可以让
123..
这样的东西通过。所以你可以这样做:我们让
float(num)
处理num
是否看起来像有效的浮点。你知道吗你可以写
换句话说,如果在第二位小数点后有任何东西。。。你知道吗
相关问题 更多 >
编程相关推荐