有人带着这个例子给我(python2):
num = int(input("num")) den = int(input("den")) quot = 0 rest = den i = num for i in range(i,i>den, -den): quot = quot + 1 rest = i - den print quot print rest代码运行正常,执行它需要做的事情,并且不会产生错误。
我不明白为什么。 对我来说, range()需要一个下限和一个上限,对我来说, i会是较低的值,而i>den应该评估为一个布尔值?
上下文是一个教程函数,它使用for循环实现除法。
Someone came with this example to me (python2):
num = int(input("num")) den = int(input("den")) quot = 0 rest = den i = num for i in range(i,i>den, -den): quot = quot + 1 rest = i - den print quot print restThe code runs fine, does what it needs to be doing, and doesn't produce errors.
I don't understand why. To me, range() requires a lower and an upper limit, and to me, i would be the lower value, while i>den should evaluate to a boolean?
The context is a tutorial function which implements division with a for loop.
最满意答案
这是“ 鸭子打字 ”的应用。 在这种情况下, i>num计算为布尔值True或False ,但在range函数的上下文中, True等于整数1 , False等于整数0 。
因此,例如,如果i>num为False ,则该代码等效于
for i in range(i, 0, -num): #do stuffThis is an application of "duck typing". In this case, i>num evaluates to a boolean value of True or False, but in the context of the range function, True is equivalent to the integer 1, and False is equivalent to the integer 0.
So, for example, if i>num is False, then that code is equivalent to
for i in range(i, 0, -num): #do stuff更多推荐
发布评论