Python对Int值的错误识别 [英] Python misidentification of int values

查看:212
本文介绍了Python对Int值的错误识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在编写一个依赖于其他函数来返回答案的函数.完成后,它表示我在某处错误地使用了"*".我经历了所有事情,看不到问题.我终于发现这是因为先前定义了一个简单的阶乘函数,如下所示:

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)

但是,如果我输入n = 6,它将返回6是一个浮点数,从而退出该函数的其余部分,我希望有人能够回答为什么会发生这种情况以及如何解决它.

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.

非常感谢

推荐答案

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

即使n >= 0(type(float))部分也将返回floattype,并且该值是非空值或Truthy值.因此,该条件将始终得到满足.您需要的是isinstance

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):

但我建议

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

现在,如果n不是int,则将引发错误.

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

这篇关于Python对Int值的错误识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆