Python,在for循环中有条件(Python, have a condition in a for loop)

编程入门 行业动态 更新时间:2024-10-24 19:13:54
Python,在for循环中有条件(Python, have a condition in a for loop)

有人带着这个例子给我(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 rest

The 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 stuff

This 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

更多推荐

本文发布于:2023-08-01 20:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1363655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   条件   Python   condition   loop

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!