数字1,10和2都有效,但2.0无效
def get_number():
number = 0
while int(number) < 1 or int(number) > 10:
if type(number) == str:
pass``
else:
try:
number = int(input("Enter a number: "))
except:
pass
return float(number)
10的输出应为10.0,1的应为1.0,2.0的应为2.0
答案 0 :(得分:0)
失败的原因是因为Python在针对表示浮点数的字符串运行代码时会引发ValueError
。参见:
23:12 $ python
Python 2.7.15 (default, Mar 4 2019, 16:04:02)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int('2.0') # Note the string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2.0'
>>> int(2.0) # Float
2
有很多方法可以改善您的代码,因此,我现在就来考虑一下:-)
仅供参考:您最初将其标记为python-3.x
,但是由于except
为空,因此代码对Python 3无效。我建议进一步查找有关异常处理的最佳实践。