上周我用python写了一个作业,下面是一个代码片段
def departTime():
'''
Calculate the time to depart a packet.
'''
if(random.random < 0.8):
t = random.expovariate(1.0 / 2.5)
else:
t = random.expovariate(1.0 / 10.5)
return t
你能看出问题所在吗?我比较一下随机。随机0.8,即 应该是随机。随机(). 在
当然这是因为我的粗心,但我不明白。在我的 看来,这种比较至少应该引起一个警告 任何编程语言。在
那么为什么python忽略它并返回False呢?在
因为在Python中,这是一个非常有效的比较。Python不知道您是真的想进行这种比较,还是只是犯了一个错误。您的工作是为Python提供合适的对象进行比较。在
由于Python的动态特性,您可以将几乎所有内容与几乎所有内容进行比较和排序(这是一个特性)。在本例中,您将函数与float进行了比较。在
例如:
这将产生以下输出:
^{pr2}$这在python3http://docs.python.org/3.1/whatsnew/3.0.html#ordering-comparisons中是“修复的”。在
这并不总是一个错误
首先,为了弄清楚,这并不总是一个错误。在
在这种情况下,很明显这种比较是错误的。在
但是,由于Python的动态特性,请考虑以下代码(如果很糟糕,则完全有效):
比较对象时实际发生了什么?
至于实际情况,将一个函数对象与一个数字进行比较,请看一下Python文档:Python Documentation: Expressions。查看第5.9节,题为“比较”,其中指出:
这应该可以解释发生了什么,以及原因。在
顺便说一句,我不确定Python的新版本会发生什么。在
编辑:如果你想知道,Debilski的答案给出了关于Python3的信息。在
相关问题 更多 >
编程相关推荐