2014-01-12 71 views
3

我想要一个输入来继续询问输入,除非输入是一个具有两个或更少小数的数字。如何检查输入是小数?

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

你可以用这个正则表达式'\ d * \。\ d {1,2}'来检查,但是对于这个问题使用正则表达式似乎是不清楚的:) – Nil

+0

“两个或更少的小数”你的意思是只有两位数小数点后?即'1234151651.12'还好吗? – roippi

回答

2

您可以使用如在评论中提到一个正则表达式:

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 
+0

@JonClements哇,这很整洁! – BartoszKP

0

你可以写

if (yourinput%.01 != 0): 
换句话说

,如果在第2位小数点后什么...

1

由于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是否看起来像一个有效的浮动。