有没有办法让 for 循环识别它即将结束?

Is there a way to make a forloop identify it's about to end?

所以,假设我有这个 for 循环:

columns = 12
num=0
for num in range(0, columns+1):
            print(f"{num:>5d}", end=" ")

并且我想在 for 循环的最后一次迭代中跳过一行 \n。有没有办法让for循环知道这是它最后一次运行?我想在最后一个数字打印后跳过一行,而不是只添加 space.

谢谢!

您可以在循环中添加如下语句:

if num == columns:
    print("")

加一行,或者在循环后面加一个print("")。 喜欢:

columns = 12
num=0
for num in range(0, columns+1):
    print(f"{num:>5d}", end=" ")
    if num == columns:
        print("")

columns = 12
num=0
for num in range(0, columns+1):
    print(f"{num:>5d}", end=" ") 
print("")