0

So, let's say I have this for loop:

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

and I want to skip a line \n on the last iteration of the for loop. Is there a way to let the for loop know that this is the last time it will run? I wanna skip a line after the last number prints instead of just adding a space.

Thanks!

  • Does this answer your question? [What is the pythonic way to detect the last element in a 'for' loop?](https://stackoverflow.com/questions/1630320/what-is-the-pythonic-way-to-detect-the-last-element-in-a-for-loop) – Tsyvarev Mar 15 '20 at 19:54

1 Answers1

1

You can add a statement in your loop like:

if num == columns:
    print("")

to add a line, or add a print("") after the loop. Like:

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

or

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