Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

print in a loop

Consider the following codes:

(1) print in a loop with sleep + no flush
from time import sleep

for _ in range(1, 5 + 1):
    print(".", end="")
    sleep(0.5)  # sec
import std/os    # sleep

for _ in 1..5:
  stdout.write(".")
  sleep(500)  # msec

Expected behaviour: the program prints a dot, then 0.5 seconds later it prints another dot, etc.

Reality: the program seemingly doesn't do anything for a few seconds and then it prints all the dots together.

Explanation: the output is buffered during the loop. After the loop, reaching the end of the program, the content of the buffer is printed on the screen in one go.

Solution

If you want to see the dots appear one after the other slowly, with some pause between them, you need to disable the buffering. You must flush the buffer explicitly, and then the content of the buffer (just one dot) will appear on the screen immediately:

(2) with flush
import sys
from time import sleep

for _ in range(1, 5 + 1):
    print(".", end="")
    sys.stdout.flush()  # !
    sleep(0.5)  # sec
import std/os    # sleep

for _ in 1..5:
  stdout.write(".")
  stdout.flushFile()  # !
  sleep(500)  # msec

𝥶Now a dot in printed, the program waits 0.5 seconds, another dot is printed, etc.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 08, 19:31