Python Tutorial
Python Output Variables
print() displays variables. You can print several items and control the separator.
print()
The print() function outputs values to the console.
x = "Python is awesome"
print(x)Multiple Arguments
Separate arguments with commas. print() inserts a space by default.
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
print(x + y + z) # no spaces — concatenationsep and end
Change the separator and the character printed at the end.
print("A", "B", "C", sep="-")
print("Hello", end=" ")
print("World")📘 Real-World Deep Dive
Five output styles — <code>print</code>, f-strings, <code>sys.stdout.write</code>, <code>logging</code>, and rich — each suit a different scenario. Picking the right one is the difference between dev-friendly and prod-friendly.
Real-Life Scenario
A small CLI that reports progress, final summary, and structured records all from the same run — using the right tool for each.
Real-Life Example
import sys, logging
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
log = logging.getLogger("demo")
# 1) Progress bars => stderr is the convention
sys.stderr.write("scanning records...
")
for i in range(1, 4):
sys.stderr.write(f" chunk {i}/3
")
sys.stderr.flush()
# 2) Final summary => stdout, structured
print("== summary ==", flush=True)
print(f"now : {datetime.now().isoformat()}")
print(f"rows : 3")
print(f"status: ok")
# 3) Machine-readable pipe => JSON to stdout
import json
records = [{"id": i, "amount": i * 1.5} for i in range(1, 4)]
sys.stdout.write(json.dumps(records) + "
")
# 4) Real logs => via the logging framework
log.info("started")
log.warning("deprecated option = legacy")Expected Output
scanning records...
chunk 1/3
chunk 2/3
chunk 3/3
== summary ==
now : 2026-08-20T22:11:14.123456
rows : 3
status: ok
[{"id": 1, "amount": 1.5}, ...]
2026-08-20 22:11:14,123 [INFO] demo: started
2026-08-20 22:11:14,123 [WARNING] demo: deprecated option = legacyCommon mistakes
- Mixing
printwith progress messages breaks when the user pipes the output. Send progress tostderrinstead. flush=Truematters in non-interactive shells — buffered output may never reach the user.- Logging fan-out can swamp the buffer; set
socketHandlerfor high-throughput scenarios.
🚀 Performance & Best Practices
sys.stdout.writeis faster thanprintin tight loops.- For many lines, accumulate in
io.StringIOand dump once. - Use
logging.handlers.QueueHandlerto keep logging off the main thread.
🧪 Try It Yourself
- Switch the progress section to a
tqdmiterator. - Add an opt-in JSON Lines mode via
--json. - Profile
printvs.sys.stdout.writefor 100 k lines.