[英]Beginner Nested Loops Python
Beginner here in an intro to programming class at Uni learning Python.在 Uni 学习 Python 的编程课程介绍中的初学者。 I understood most of it until loops and now I am very confused.
我理解大部分直到循环,现在我很困惑。
Can someone explain why this creates the pattern that it outputs?有人可以解释为什么这会创建它输出的模式吗?
for i in range(1, 7):
for j in range(6, 0, -1):
print(j if j <= i else " ", end = " ")
print()
outer loop triggers and ( i = 1
)外循环触发 and (
i = 1
)
then inner loop triggers and ( j = 6
)然后内循环触发 and (
j = 6
)
then it doesn't print j
(6) because 6 <= 1
is False
and prints 2 blank spaces.然后它不打印
j
(6) 因为6 <= 1
是False
并打印 2 个空格。
Then at this point does the inner loop end and then goes back to the outer loop for the next iteration?那么此时内循环是否结束,然后返回到外循环进行下一次迭代?
or does the inner loop continue until 6-1 hits 1?还是内循环一直持续到 6-1 命中 1?
and if the inner loop continues, does i
stay 1 the entire inner loop or does it also go up per each inner loop iteration?如果内循环继续,
i
在整个内循环中保持 1 还是每次内循环迭代都会上升?
i really hope this makes sense.我真的希望这是有道理的。 thank you!
谢谢你!
The inner loop continues until it is exhausted, counting down with j
going from 6, to 5, to 4 and so on until on the last iteration j
is 0. While it does so the outer loop doesn't progress: i
remains 1. Only once the inner loop finishes does the outer loop get a chance to repeat.内循环一直持续到耗尽,
j
从 6 到 5,再到 4 倒计时,直到最后一次迭代j
为 0。虽然这样做,外循环不会继续: i
仍然是 1。只有当内循环完成后,外循环才有机会重复。 So then i
advances to 2
and the inner loop starts all over from 6 again.然后
i
前进到2
并且内部循环再次从 6 开始。
First outer loop: i = 1 inner loop iterates: j = 6, 5, 4, 3, 2, 1 And is False, False, False, False, False, True So produces " 1"第一个外循环:i = 1 内循环迭代:j = 6, 5, 4, 3, 2, 1 And is False, False, False, False, False, True 所以产生“1”
Second outer loop: i = 2 inner loop iterates: j = 6, 5, 4, 3, 2, 1 And is False, False, False, False, True, True So produces " 2 1"第二个外循环:i = 2 内循环迭代:j = 6, 5, 4, 3, 2, 1 And is False, False, False, False, True, True 所以产生“2 1”
Third outer loop: i = 3 inner loop iterates: j = 6, 5, 4, 3, 2, 1 And is False, False, False, True, True, True So produces " 3 2 1"第三个外循环:i = 3 内循环迭代:j = 6, 5, 4, 3, 2, 1 And is False, False, False, True, True, True 所以产生“3 2 1”
etc等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.