The print
uses stdout
, as C. This is nothing more than the "file" in the operating system to which the text output of a program is sent, and so can be shown to the user.
By default, the stdout
is bufferized; that is, it stores the data it receives without showing them until it receives the special code of new line \n
.
The function print
Python by default automatically puts a new line character in any string you send to it. But sometimes this behavior is not desired and you want to use two prints
to show something on the same line. In this case, you will use the argument end
of function print
to finish the string with something other than the new line character (or with an empty string, not to print anything other than what you sent).
For example, you can expect the following code to print multiple dots on the same line, one every 0.5s:
import time
for _ in range(5):
print('.', end='')
time.sleep(0.5)
print(' Pronto!')
But what really happens in most cases is that nothing happens for 2.5s and then all the dots appear at once.
This happens because the stdout
by default shows nothing until it gets a new line, which we are not sending until the end.
So how do we fix this problem?
Simple, just use the flush
to force the result to appear immediately, even without a new line:
import time
for _ in range(5):
print('.', end='', flush=True)
time.sleep(0.5)
print(' Pronto!')
It is worth mentioning that the flush
as a pro argument print
is only available from Python 3.3. Before that, it had to be manually called:
import sys
import time
for _ in range(5):
print('.', end='')
sys.stdout.flush()
time.sleep(0.5)
print(' Pronto!')
Comments should be added in the comment area, not reply. Take a look at the [tour] that has some cool tips on how to properly interact with the community
– Renato Junior
Depending on the amount of reputation points it is not possible to comment, so for new users it takes a while to get the amount of points needed to be able to comment on the questions
– Juven_v
Exact @Juven_v , I have no reputation to comment(I can only comment on this because I published the reply)
– Leonardo Stefan
@Renatojunior as I still have no reputation to add comment, should I edit the answer that has already been made? Apparently, no one corrected it by saying I was wrong, only it was negative because it was a comment made as a response. And I think it’s weird to edit someone else’s answer. I ask this sincerely, I want to "evolve" in Stacks, but it’s hard when you don’t have a high score to comment on, and the questions that are in the domain are already.
– Leonardo Stefan