0
0
Pythonprogramming~20 mins

Flushing and buffering concepts in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Flushing and Buffering Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of print with buffering and flush
What will be the output of this Python code snippet when run in a standard terminal?
Python
import sys
print('Hello', end='')
sys.stdout.flush()
print(' World')
AHello\n World
BHello World
CHelloWorld
DHello
Attempts:
2 left
💡 Hint
Think about how flush affects the output buffer and the end parameter in print.
Predict Output
intermediate
2:00remaining
Effect of buffering on file write
Consider this code writing to a file. What will be the content of 'output.txt' immediately after running this code?
Python
with open('output.txt', 'w') as f:
    f.write('Line 1\n')
    # No flush or close yet
    f.write('Line 2\n')
AFile contains both 'Line 1\nLine 2\n'
BFile is empty
CFile contains only 'Line 1\n'
DFile contains only 'Line 2\n'
Attempts:
2 left
💡 Hint
Think about when the file is closed and how Python buffers file writes.
Predict Output
advanced
2:00remaining
Output of print with delayed flush in a loop
What is the output of this code snippet?
Python
import time
for i in range(3):
    print(i, end=' ', flush=False)
    time.sleep(1)
print('Done')
A0\n1\n2\nDone
B0 1 2 \nDone
CDone0 1 2
D0 1 2 Done
Attempts:
2 left
💡 Hint
Consider that flush=False means output may be buffered until newline or program ends.
Predict Output
advanced
2:00remaining
Behavior of sys.stdout with buffering
What will this code print when run in a Python script executed in a terminal?
Python
import sys
sys.stdout.write('Start')
sys.stdout.flush()
sys.stdout.write('End')
AStart\nEnd
BStart
CStartEnd
DEnd
Attempts:
2 left
💡 Hint
Remember that sys.stdout.write does not add newlines and flush controls output buffering.
Predict Output
expert
3:00remaining
Output of print with buffering and os.write
What is the output of this code snippet?
Python
import os
import sys
print('Hello', end='')
os.write(sys.stdout.fileno(), b'World\n')
AWorld\nHello
BHello\n World
CHello World
DHelloWorld\n
Attempts:
2 left
💡 Hint
os.write bypasses Python buffering and writes directly to the file descriptor.