import sys print('Hello', end='') sys.stdout.flush() print(' World')
The first print outputs 'Hello' without a newline and flushes the buffer immediately, so 'Hello' appears right away. The second print adds ' World' with a newline, so the combined output is 'Hello World'.
with open('output.txt', 'w') as f: f.write('Line 1\n') # No flush or close yet f.write('Line 2\n')
The 'with' block ensures the file is closed at the end, which flushes all buffered writes. So both lines are written to the file.
import time for i in range(3): print(i, end=' ', flush=False) time.sleep(1) print('Done')
With flush=False (default) and end=' ', the outputs from the loop ('0 1 2 ') are buffered. When print('Done') executes, it appends 'Done\n' to the buffer. Since stdout to terminal is line-buffered, the newline causes the full buffer '0 1 2 Done\n' to flush at once after the sleeps.
import sys sys.stdout.write('Start') sys.stdout.flush() sys.stdout.write('End')
Both writes output text without newline. The flush after 'Start' forces it to appear immediately. 'End' is written but not flushed explicitly, but the program ends so output is flushed automatically. The combined output is 'StartEnd'.
import os import sys print('Hello', end='') os.write(sys.stdout.fileno(), b'World\n')
The print outputs 'Hello' without newline but is buffered. os.write writes 'World\n' directly to the file descriptor, bypassing Python's buffer, so it appears first. At program end, the buffer flushes 'Hello' after it. Output: World\nHello