Python misidentification of int values

吃可爱长大的小学妹 提交于 2019-12-24 03:58:31

问题


I have been for some time writing a function which relies on many other to return an answer. When I finished it, it stated I had wrongly used the "*" somewhere. I went through everything and could not see a problem. I finally found that it was because of a simple factorial function earlier defined, as shown below:

if n == 0:
    return 1
elif n < 0 or (type(float)):
    print "%s is an invalid input; Positive integer value is required" % (n)
else:
    return (n)*fact(n-1)

However if I enter n = 6, it returns that 6 is a floating number, and thus exits the rest of the function, and I hope someone can answer why this is happening and how to get around it.

Many Thanks


回答1:


elif n < 0 or (type(float)):

Even when n >= 0, (type(float)) part will return the type of float and that is non-empty or Truthy value. So, the condition will be met always. What you need is, isinstance

elif n < 0 or isinstance(n, float):

But I would suggest,

elif not isinstance(n, int) or n < 0:

Now, if n is anything other than an int the error will be thrown.




回答2:


Your second condition should be isinstance(n, float):

if n == 0:
    return 1
elif n < 0 or isinstance(n, float):
    print "%s is an invalid input; Positive integer value is required" % (n)
else:
    return (n)*fact(n-1)

Indeed, as you can see below, isinstance check the type and the built-in type returns a type:

>>> isinstance(1.0, float)
True
>>> isinstance(1, float)
False
>>> type(float)
<type 'type'>


来源:https://stackoverflow.com/questions/21969453/python-misidentification-of-int-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!