简体   繁体   English

这个嵌套 for 循环在 Python 中是如何工作的?

[英]How this nesting for loop works in Python?

I can't understand the second for loop:我无法理解第二个 for 循环:

for k in range(2, n//2 + 1):
    print(n%k, end=" ")

How did this formula produce such result?这个公式是如何产生这样的结果的?

在此处输入图片说明

range() has multiple parameters, first is start, second is stop, third is step (which is not present in this example, so the default value is used: 1 ). range()有多个参数,第一个是 start,第二个是 stop,第三个是 step(在这个例子中不存在,所以使用默认值: 1 )。

So your range will generate numbers from 2 to n//2 + 1.因此,您的范围将生成从 2 到 n//2 + 1 的数字。

To learn more about range, and for loops:要了解有关范围和 for 循环的更多信息:

https://www.w3schools.com/python/ref_func_range.asp https://www.w3schools.com/python/python_for_loops.asp https://www.w3schools.com/python/ref_func_range.asp https://www.w3schools.com/python/python_for_loops.asp

The second for loop prints the reminders of dividing n by all of the numbers from 2 to n/2.第二个 for 循环打印将 n 除以从 2 到 n/2 的所有数字的提示。

check the documentation of range检查范围的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM