0

Given this code:

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

How can I let the for loop know that this is the last time it will run, so that I can add a newline after the entire output (instead of a space)?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    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