英文:
Triangle number: for nested loops in Python
问题
n = int(input())
for a in range(0, n+1):
for j in range(1, a+1):
print(j, end=' ')
print()
输入:
5
输出:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
在练习编程时,我遇到了一个问题。当我看到这段代码时,我不知道它是如何工作的。请帮我回答大家!谢谢大家! :))
英文:
Code snippet
n = int(input())
for a in range(0, n+1):
for j in range(1, a+1):
print(j, end=' ')
print()
Input:
5
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
I had a problem while practicing coding. When I came across this piece of code, I didn't know how it worked. Please help me answer everyone!
Thanks everyone! :))
答案1
得分: 1
我的猜测是你不理解的部分是这一行:
print(j, end=' ')
它的作用是打印数字 j
,然后使用 ' '(即空格)作为结束字符。
通常情况下,使用 print
函数时,默认的结束字符是 \n
(在mac/linux上)或 \r\n
(在Windows上),它表示换行,下一个 print
会在新的一行打印。
在这里,数字被打印出来,然后打印一个空格,而没有换行。下一个数字会在同一行的空格后面打印,因为我们没有打印换行符。
在每个第一层循环的结尾,有一个 print()
,它实际上什么都不打印,但使用默认的结束字符,因此打印一个新行,下一个循环从那个新行开始。
对于这些行:
for a in range(0, n+1):
for j in range(1, a+1):
第一行执行一个循环,范围是从 0 到 n(步长为1)。range
是左闭右开的,也就是说如果 n = 3,它会遍历 0、1、2、3。
第二个循环类似,但是范围是从 1 到 a + 1,其中 a 是第一个循环的值,因此它在每次循环运行时递增。
第二个循环运行在第一个循环内部,因此当 a = 0 时,它运行 1 到 1(1次)并打印 1
,然后当 a = 2 时,它运行 j = 1 和 j = 2,并打印 1 2
,当 a = 3 时,第二个循环运行 j = 1、j = 2、j = 3 并打印 1 2 3
,以此类推。
第一个循环运行 n 次,所以如果 n = 5,它会打印 5 行。
英文:
my guess is that the part you don't understand is this line:
print(j, end=' ')
What it does is print the number j
, and then uses ' ' (i.e. space) as the end character.
Usually with the print
function, the default end character is \n
(on mac/linux) or \r\n
on Windows which is a line feed, and the next print
prints on a new line.
Here the number is printed, and then a space is printed, without a line feed. The next number is then printed on the same line after the space because we didn't print a line feed.
At the end of each first loop, there is a print()
, which effectively prints nothing but a uses the default end character, and therefore prints a new line, and the next loop over the numbers starts at that new line.
for the lines:
for a in range(0, n+1):
for j in range(1, a+1):
the first line does a for loop over the range 0 to n (with a step size of 1). the `range is inclusive on the left and exclusive on the right, that is if n = 3, it goes over 0, 1, 2, 3
Second loop is the same but over 1 to a + 1, a being the value from the first loop, so it increases at each run of the loop.
The second loop runs inside the first one, so when a = 0, it runs 1 to 1 (1 time) and print 1
, then a = 2, it runs for j = 1 and j = 2, and prints 1 2
, when a = 2, second loop runs for j = 1, j= 2, j = 3, and print 1 2 3
and so on.
The first loop runs n times, so if n = 5 it prints 5 lines.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论