A version of str.isdigit that returns True for decimal fractions?
本问题已经有最佳答案,请猛点这里访问。
我想测试
理想情况下,代码如下所示:
1 2 3 4 5 6 7 8 9 10 | def enter_number(): number = raw_input("Enter a number:") # I enter 3.5 if number.SOMETHING: # SOMETHING is what I am looking for float_1 = float(number) return float_1 else sys.exit() half = enter_number() / 2 # = 1.75 double = enter_number() * 2 # = 7 |
我建议采用EAFP方法。
如果参数不是有效的float,那么
1 2 3 4 5 6 7 | In [6]: float('bad value') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-6-dc9476bbdbf8> in <module>() ----> 1 float('bad value') ValueError: could not convert string to float: 'bad value' |
你可以抓住它:
1 2 3 4 5 | number = raw_input("Enter a number:") try: return float(number) except ValueError: sys.exit() |