[英]Basic Python For-Loops
我很抱歉问愚蠢的问题。
我正在通过视频和书籍学习 Python,真的没有其他帮助。
无法弄清楚基本 python 编程的简单区别。
#####################################AAAAAA def sum_cart(item):
total_cost = 0
for this in costs:
total_cost = this + total_cost
return total_cost
print sum_cart(costs)
#####################################BBBBBB
def sum_cart(item): total_cost = 0 for this in costs: total_cost = this + total_cost return total_cost print sum_cart(costs)
######################################CCCCCC
def sum_cart(item): total_cost = 0 for this in costs: total_cost = this + total_cost return total_cost print sum_cart(costs)
- - - - - -问题 - - - - - -
结果是 A --> 0, B --> 50, C --> 5
我仍然很困惑为什么结果显示为原样。
如果我的理解是正确的,在 A 中,'this' 从列表中获取 5,并将 5 添加到 total_cost,即 0。然后 'this' 分别调用 10、15 和 20,并且 'this' 获得一个新值。 但是,因为total_cost 仍然是0,所以结果是0。我说的对吗?
然后在 B 中,当调用 'this' = 5 时更新 total_cost 并将其添加到当前的 'total_cost' = 0,即 5。循环返回并分别引入 10、15 和 20 以及 'total_cost'已更新至 50。到目前为止,我认为还不错。
但是在 C 中,我不确定发生了什么,因为当 'this' 从列表中带来 5 的值时,'total_cost' 会更新。 然后它应该将'total_cost'返回到5。for循环不应该返回并执行total_cost = this(假设为10)+ total_cost(当前为5)并再次执行循环? 我对“返回”功能缺少什么?
您的前两个假设是正确的。
在 C 中, return
立即退出函数。 此时循环中止,返回total_cost
(此时为 5)。
这三个人都写得有问题。 你应该写一些更像这样的东西:
costs = [5,10,15,20]
def sum_cart(items):
total = 0
for item in items:
total = total + item
return total
print sum_cart(costs)
即使你的例子 B,虽然它得到正确的答案是错误的,因为你传入了参数item
,但在你的循环中你循环了全局可变costs
(所以你实际上并没有使用你传递给的参数你的功能)。
return
从整个函数返回并结束它。 在您的第三个示例中,for 循环只能运行一次。 在第一次运行结束时,该函数返回并且 for 循环的其余部分永远不会发生。
return
总是结束它所在函数的执行。
因此,在您的最后一个示例中,一旦函数到达return
, sum_cart()
函数就会结束,返回total_cost
(第一次遇到它时,它等于 5。
of your for loop, which is why they don't return the value until they've finished iterating over your array.请注意,在其他两个例子中, return
语句位于你的for循环,这就是为什么他们,直到他们已经完成迭代在你的阵列没有返回值。
在样本 A 中,total_cost 从来都不是零。 您从 total_cost 中取零值并将其添加到其他内容中 - 这也不会更改该值。
在示例 B 中,您每次都将this
任何值添加到 total_cost 中。 因此,它会随着您的进行而累积价值。 python中等号左侧的任何内容都采用右侧表达式的值。
在示例 C 中,您的缩进不同,并且 return 语句位于 for 循环内。 这将导致函数 sum_cart 在遇到这行代码时立即返回 total_cost 的当前值(第一次通过 for 循环)。 Return 不只是将您从循环的当前迭代中引导出来,它还将您从您所在的任何函数中引导出来,因为 return 字面意思是“返回到我(我是这里的函数)最初被调用的地方。你可以选择返回一个值,就像你在这里做的那样。
不应该拼写
for this in item:
代替
for this in costs:
?
情况 C:
一旦循环中的第一次迭代遇到“return”,函数就会结束。 循环建立在函数内部,函数已经结束。 因此,循环停止。
第一次迭代结束时返回的值为 total_cost:5。
实际上,代码 A 看起来接近正确的答案,只是函数中的参数是“item”并且您正在迭代列表“costs”。 并且逻辑可以更正为 total_cost+=this 因为我们有兴趣增加 total_cost 而不是 'this' 变量。 你可以试试这个代码;
costs = [5,10,15,20]
def sum_cart(costs):
total_cost = 0
for this in costs:
total_cost += this
return total_cost
print sum_cart(costs)
希望这个回答有帮助...
在示例 A 中- 您在this中求和 this 的值并返回total_cost ,它仍然为 0。
在示例 B 中- 它在语义上是正确的。 您正在对total_cost 中的 list 值求和并返回total_cost 。
在示例 C 中- 返回在 for 循环中,因此列表的第一个值在total_cost 中求和,并返回total_cost 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.