Search code examples
pythonfor-loopiterationnewlinestring-formatting

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


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)?


Solution

  • 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("")