Why does my print execute after the second loop even if I use print first?

Question:

I’m a beginner of python, and I wanted to try to make a timer.

import time

sets=int(input("How many sets?: "))
seconds=int(input("How many seconds per set?: "))

for i in range(sets):
    print("set {0} of {1} started".format(i + 1, sets))
    for j in range(seconds, 0, -1):
        print(j, end=" ")
print("Finished workout! Good Job!")

The problem is that the first print in the first loop is active after the j loop is ended, and I don’t know why.
Also my version of py is 3.11, I’m sorry if I misinterpreted the python-3.x tag.

I expected the output to be:

How many sets?: 3
How many seconds per set?: 2
set 1 of 3 started
2 1
set 2 of 3 started
2 1
set 3 of 3 started
2 1
Finished workout! Good Job!

But it’s

How many sets?: 3
How many seconds per set?: 2
2 1 
set 1 of 3 started
2 1 
set 2 of 3 started
2 1 
set 3 of 3 started
Finished workout! Good Job!

Please help and thank you! 🙂

Asked By: David Munteanu

||

Answers:

By default print terminates with a newline character. When you define end in the print function, you modify this behavior. I have added a bare print which will simply output a newline character to stdout, correcting the format issues.

for i in range(sets):
    print("set {0} of {1} started".format(i + 1, sets))
    for j in range(seconds, 0, -1):
        print(j, end=" ")
    print()
print("Finished workout! Good Job!")

I would also like to add, that if you’re on windows and using something like git-bash or powershell to test your code, you may need to flush stdout after a print to have your text displayed in the proper order.

print("Hello World!", flush=True)

If this applies to your situation, make sure you test, as over flushing the buffer can cause a lot of lag in your application.

Answered By: Jarrod Burns
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.