确保输入是一个浮点数

时间:2017-05-02 09:11:36

标签: python python-3.x input

我目前的代码:

while True:
    surjuv = input("What is the juvenile survival rate?")
    if surjuv.isinstance(float)==True and float(surjuv)<=1 and float(surjuv)>=0:
        break

需要确保surjuv是浮点数,但输入0.5时会出现以下错误:

Traceback (most recent call last):
File "python", line 81, in <module>
File "python", line 21, in main_menu
File "python", line 51, in enter_gen0
AttributeError: 'str' object has no attribute 'isinstance'

1 个答案:

答案 0 :(得分:5)

isinstance的语法为isinstance(surjuv, float),但在您的情况下这总是会失败,因为Python 3 input会返回一个字符串。

将输入转换为float,如果失败则执行任何必要的错误处理。

try:
    surjuv = float(input('...'))
except ValueError:
    continue # or whatever you want