Programming with Python βΊ Python Setup and First Programs βΊ Day 47
Day 47: Input, Output, and f-strings
After this lesson you will be able to read input safely from a prompt, a pipe, or a command-line argument, format values into clean aligned output with f-string format specs, and separate results from errors so your program behaves well inside a shell pipeline.
Hands-on lab for this lesson
Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/programming-with-python/day-047-input-output-and-f-strings
- Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git cd ai-roadmap-365.github.io - Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path β section / subsection / week / day:
cd labs/sections/programming-with-python/day-047-input-output-and-f-strings - Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work β read it before running anything.
- Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
bash tests/run_tests.sh # or the test command named in the lab README
You can also open the lab as a local page (works offline, shows the file tree and expected output).
Learning objectives
By the end of this lesson you will be able to:
- Use print() fully β sep, end, file, and flush β and explain what each argument controls
- Explain why input() always returns a str and convert its result to a number safely with int() or float()
- Read and apply the f-string format specification for alignment, width, precision, thousands separators, dates, and expressions
- Name the three standard streams (stdin, stdout, stderr) and route results to stdout and diagnostics to stderr so a pipeline stays clean
- Read command-line arguments from sys.argv and read piped data from sys.stdin, and choose between input(), sys.argv, and sys.stdin for a given task
- Open and write a file safely with open() and a with-statement context manager, and state why eval() must never be used on input
Prerequisites
- Days 43-46: a working Python 3 install, variables and types, strings, and numbers
- Day 10: the shell and pipes (stdout of one program feeding stdin of the next)
- A terminal on macOS or Linux (or WSL on Windows)
Why this matters
-
Every program talks to the outside world through these three streams, and Day 10βs pipes depend on your using them correctly.
-
input()always returns a string, and forgetting that is the most common first bug in Python. -
f-strings format every number you will ever print β a loss, a percentage, an elapsed time.
-
Writing progress to
stdoutcorrupts a pipeline. Progress belongs onstderr, and that separation is Day 10βs, in Python. -
with open(...)is how every dataset is read, and the context manager is what closes the file when a run fails halfway.
The idea in plain language
-
Three streams, from Day 6: standard input, standard output, standard error.
-
print()writes tostdout;input()reads fromstdin. -
Data goes to
stdout; commentary goes tostderr. That is the whole rule. -
input()returns text, always. Converting it is your job, and so is handling the conversion failing. -
withguarantees the file closes, whatever happens inside the block.
Historical background
-
The three streams predate Python by decades β they are Unixβs, from the 1970s, and Day 10 is where you met them.
-
Python inherited them unchanged, which is why a Python program drops into a shell pipeline without adaptation.
-
printwas a statement in Python 2 and became a function in Python 3, which was one of the most visible breaking changes of that migration. -
Making it a function was right: it can be passed around, its arguments can be keyword-controlled, and
sep,end,fileandflushbecome ordinary parameters rather than special syntax. -
The
withstatement arrived in Python 2.5, in 2006, to make cleanup automatic rather than remembered. -
f-strings came in 3.6 and are now the only formatting syntax worth writing.
What it is β and what it is not
These streams are:
- File-like objects your program is handed at startup, from Day 6.
- Redirectable by the shell, without the program knowing.
- The interface that makes a program composable.
They are not:
-
Not the terminal. They may be a file, a pipe, or another program, and your code cannot assume.
-
Not interchangeable.
stdoutcarries the result;stderrcarries everything else. -
Not line-buffered when piped. Output to a pipe is block-buffered, which is why long-running programs need
flush=Trueto show progress. -
Not typed. Everything crossing them is text or bytes, so
input()cannot give you a number.
Why it was created and what problems it solves
-
Composition. A program that reads
stdinand writesstdoutjoins any pipeline, as Day 10 showed. -
Separating results from commentary, so errors do not contaminate data.
-
Redirection without cooperation. The shell rewires the streams and the program is none the wiser.
-
Guaranteed cleanup.
withcloses a file on the way out, including when an exception is raised β which aclose()at the bottom of a function does not. -
Readable formatting. f-strings put the value where it appears rather than in a separate argument list.
How it works
The three streams
print()writes tostdoutby default.print(..., file=sys.stderr)writes tostderr.input()reads a line fromstdin, stripped of its newline.- The shell decides where each one goes, per Day 10βs redirection table.
print() in depth
print("a", "b", sep="-", end="") # a-b, with no newline
print("progress", file=sys.stderr, flush=True)
sepgoes between the arguments; the default is a single space.endgoes after them; the default is a newline.filechooses the stream.flush=Trueforces the write out immediately. Without it, output to a pipe is block-buffered and appears in chunks β which is why a progress line seems to hang and then dump.
input(), and the trap
age = input("Age: ") # always a str, even for "42"
age = int(input("Age: ")) # raises ValueError on "abc"
-
It always returns a string.
input() + 1raises;input() * 2duplicates the text rather than doubling a number. -
Converting can fail, so a program that must not crash needs
try/exceptaround it. -
The prompt goes to
stdout, which means it is captured when you pipe the program β one reason interactive prompts and pipelines mix badly. -
In a script that runs unattended, do not use
input()at all. Take an argument instead.
f-strings for output
f"{loss:.4f}" # 0.0317
f"{acc:.1%}" # 91.4%
f"{n:,}" # 1,234,567
f"{name:>12}" # right-aligned in twelve columns
f"{value=}" # value=0.0317 β prints the expression too
- The
=form is the debugging one, and it saves writing the label by hand. - Width does not truncate. A longer value overflows its column rather than being cut.
Files, and why with
with open("data.csv", encoding="utf-8") as f:
for line in f:
...
-
withcloses the file on the way out, including when an exception is raised inside the block. -
Iterating a file yields lines, one at a time, without loading the whole thing β which is Day 10βs streaming, in Python.
-
Always pass
encoding. The default varies by platform, and Day 5βs mojibake follows from leaving it to chance. -
Text mode gives
str; binary mode ("rb") givesbytes.
Command-line arguments
import sys
target = sys.argv[1] if len(sys.argv) > 1 else "."
sys.argv[0]is the scriptβs own name; the arguments start at index 1.- They are always strings, exactly like
input(). - This is Day 12βs positional parameters, in Python.
argparseis the real answer for anything with options, and it is Day 80.
An everyday analogy
A machine on a factory line.
| The line | The program |
|---|---|
| The input hopper | stdin |
| The output chute | stdout |
| The reject chute | stderr |
| The settings dial | Command-line arguments |
| Asking an operator a question | input() |
| The machine not caring what comes next | Redirection |
| Closing the hatch when you leave | with |
-
The machine does not know what feeds it or what it feeds. That is what lets it be dropped into any line.
-
The reject chute is separate on purpose. Mixing rejects into the output is how a whole batch gets contaminated.
-
Asking an operator a question stops the line working unattended.
Examples in practice
-
TypeError: can only concatenate strafterinput(), which is the trap in its most common form. -
A progress bar that appears all at once at the end, because the output was block-buffered into a pipe.
-
A script whose progress messages end up in the data file, because they went to
stdout. -
A file left open after an exception, in code that called
close()at the bottom of the function. -
Mojibake reading a CSV, because
encodingwas left to the platform default.
Implications: security, privacy, performance, scalability, and cost
-
Security: never
eval()whatinput()returned. It is untrusted text, and evaluating it runs whatever was typed. -
Do not build a shell command from an argument by concatenation β Day 45βs injection rule, arriving through a different door.
-
Privacy: prompting for a password with
input()echoes it.getpassexists precisely for that. -
Performance:
printin a tight loop is slow, because each call may flush. Build a list and write once, or write to a buffered stream. -
Iterating a file is streaming;
f.read()loads the whole thing. On a large file that is the difference between flat memory and none. -
Cost: an unclosed file handle leaks. A long-running process that opens files in a loop without
withwill eventually exhaust its descriptors β Day 17βs limit, reached from a different direction.
Alternatives: free, open source, and commercial
| Tool | Type | Where it fits |
|---|---|---|
print / input | Free, built in | Everything simple |
sys.stdout.write | Free, built in | When you want no automatic newline at all |
argparse | Free, standard library | Real command-line interfaces β Day 80 |
getpass | Free, standard library | Reading a secret without echoing it |
pathlib | Free, standard library | Paths, and Path.read_text() for small files |
logging | Free, standard library | Anything long-running; levels and destinations |
-
Move from
printtologgingthe moment a script runs unattended. Day 40βs argument: a job with no log is a job you cannot diagnose. -
pathlibis the modern way to touch the filesystem, andPath("x").read_text()is often all a small file needs.
Comparison with related concepts
| Term | What it actually is |
|---|---|
stdin | The stream a program reads from |
stdout | Where its results go |
stderr | Where its commentary goes |
| Buffering | Holding output until there is enough to write |
flush | Forcing the buffer out now |
| Context manager | The object with sets up and tears down |
sys.argv | The command line, as a list of strings |
When to use it β and when not to
- Write results to
stdoutand everything else tostderr. Always. - Use
withfor every file, without exception. - Pass
encoding="utf-8"explicitly. - Use
flush=Truefor progress that must appear as it happens. - Do not use
input()in a script that runs unattended. Take an argument. - Do not use
f.read()on a file you cannot afford to hold in memory. - Do not print in a tight loop when you could accumulate and write once.
The AI connection
-
Streaming a modelβs output is
print(..., flush=True)or writing tostdoutdirectly β without the flush, tokens arrive in blocks rather than as they are generated. -
stdoutis for data andstderris for progress. A training script that logs progress tostdoutcorrupts anything piping its results. -
Every training script takes command-line arguments, and
sys.argvis the raw form beneath every frameworkβs argument parser. -
with open(...)is how datasets are read, and the context manager is what guarantees the handle closes when a run fails halfway. -
f-strings format every metric you will print β loss to four decimals, accuracy as a percentage, elapsed time with a thousands separator.
Knowledge check
quiz:
question: "A script prints progress messages and its results, and works correctly when run in a terminal. Piped into another program, the downstream tool receives the progress lines mixed into its data. What is wrong?"
options:
- "The progress messages are written to stdout, which is the stream the pipe carries"
- "The pipe merges stdout and stderr unless the program disables it"
- "The script needs flush=True so the streams stay in order"
- "print() cannot write to stderr, so progress must go to a file instead"
answer_index: 0
explanation: "A pipe carries stdout only, which is exactly why the separation exists. Progress written with a plain print() goes to stdout alongside the results; sending it to stderr with file=sys.stderr keeps it on screen and out of the data."
Hands-on exercise
Separate the streams, then prove it with a pipe. Worked through fully in the Day 47 lab directory.
| What you are doing | Command |
|---|---|
| Write to both streams | print("data") and print("note", file=sys.stderr) |
| Prove the pipe carries one | python3 s.py | wc -l |
| Send errors to a file | python3 s.py 2> errors.txt |
| See the input trap | int(input()) with abc typed |
| Format numbers | f"{0.03174:.4f}", f"{0.914:.1%}", f"{1234567:,}" |
| Read a file safely | with open(p, encoding="utf-8") as f: |
| Take an argument | sys.argv[1] if len(sys.argv) > 1 else "." |
Expected output
data
note
1
ValueError: invalid literal for int() with base 10: 'abc'
0.0317 91.4% 1,234,567
-
wc -lcounted 1, not 2 β the note went tostderrand the pipe never saw it. -
Both appeared on screen when run directly, which is why the bug hides until the program is piped.
Validate your work
- You wrote to both streams and proved a pipe carries only one
- You redirected
stderrto a file separately - You handled a failed
int(input())without the program crashing - You formatted a float, a percentage and a thousands-separated integer
- Every file you opened used
withand an explicitencoding -
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
Output appears only at the end. Block buffering into a pipe. Add
flush=True. -
input()returns nothing under a pipe.stdinis the pipe, not the keyboard. That is the point. -
UnicodeDecodeErrorreading a file. The encoding is not what you assumed. Day 5. -
IndexErroronsys.argv[1]. No argument was given. Checklenfirst.
Common mistakes
- Progress on
stdout. - Forgetting
input()returns a string. open()withoutwith.- Leaving
encodingto the platform default.
Practice assignment
-
Write a filter: read
stdin, transform each line, writestdout, report counts onstderr. Then use it in a pipeline withgrepandsort. -
Convert an interactive script to an argument-driven one, and run it under
cronper Day 14. -
Format the same number six ways β decimals, percentage, separators, alignment, width, and the
=debug form. -
Open a file without
with, raise an exception inside, and confirm the handle leaked.
Extension challenge
-
Measure buffering. Time a loop printing 100,000 lines with and without
flush=True, to a terminal and to a pipe, and explain all four numbers. -
Write a context manager of your own with
contextlib.contextmanager, and prove its cleanup runs when the block raises. -
Read a file larger than memory line by line and compute a statistic, then try
f.read()on it and watch what happens. -
Handle a broken pipe. Pipe a long-running script into
headand catch the resulting error rather than letting it traceback.
Quiz
Q1. A learner writes total = input("a: ") + input("b: "), types 5 then 7, and finds total is "57". What happened?
- input() returned numbers, but + concatenated them by mistake
- Python added 5 and 7 but displayed the result in a different base
- input() always returns a string, so + joined "5" and "7" instead of adding
- input() only reads one character at a time
Show answer
Answer: C. input() always returns a string, so + joined "5" and "7" instead of adding
input() always returns a str, even for digits, so "5" + "7" is string concatenation, giving "57". Converting with int() first β int(input(...)) β makes it real addition that gives 12.
Q2. Which print() keyword argument forces buffered text out to the terminal immediately, as needed for a live progress indicator or streamed output?
- end
- sep
- file
- flush
Show answer
Answer: D. flush
flush=True forces Python to write the output buffer out at once instead of collecting it. sep sets the separator between values, end sets what follows the last value, and file chooses the destination stream.
Q3. What does the format spec in f"{price:>10.2f}" do to the value?
- Right-aligns it in a field 10 characters wide with exactly 2 decimal places
- Left-aligns it in 10 characters with 2 significant figures
- Pads it with 10 zeros and rounds to 2 decimals
- Prints it in scientific notation with 2 digits
Show answer
Answer: A. Right-aligns it in a field 10 characters wide with exactly 2 decimal places
The > means right-align, 10 is the minimum field width, and .2f means fixed-point with two decimal places. For price = 7.5 it produces " 7.50" β six padding spaces plus "7.50", ten characters in all.
Q4. In a shell pipeline like cat data.txt | python3 tool.py | sort, why must tool.py send its error messages to standard error rather than standard output?
- Standard error is faster than standard output
- Errors on standard output would flow down the pipe
- Standard output cannot display red text
- sort only reads from standard error
Show answer
Answer: B. Errors on standard output would flow down the pipe
Standard output is the data channel that feeds the next program through the pipe. If errors went there too, they would be mixed into the data stream sort tries to parse. Standard error is a separate channel that stays on the terminal, keeping the pipe clean.
Q5. Which value does sys.argv[0] hold when you run python3 greet.py Ada 30?
- The first real argument, "Ada"
- The number of arguments, 2
- The script name, "greet.py"
- The Python interpreter path
Show answer
Answer: C. The script name, "greet.py"
sys.argv[0] is the script name itself; the actual arguments start at index 1, so sys.argv[1] is "Ada" and sys.argv[2] is "30" β and, like input(), those items are strings that need converting for arithmetic.
Q6. Why should you never write eval(input()) to turn user input into a value?
- eval() is slower than int()
- eval() rounds numbers incorrectly
- eval() only works on numbers, not text
- eval() executes the input as Python code
Show answer
Answer: D. eval() executes the input as Python code
eval() runs its text argument as Python code, so eval(input()) lets whoever supplies the input execute anything on your system. To turn text like "42" into a number, use int() or float(), which parse a value and nothing more.
Q7. What is the correct, safe way to open a file for writing so it is always closed, even if an error occurs mid-write?
- with open("out.txt", "w") as f:
- f = open("out.txt", "w") and remember to call f.close() at the end
- open("out.txt", "w").write(...) on one line
- eval(open("out.txt"))
Show answer
Answer: A. with open("out.txt", "w") as f:
The with statement uses the file as a context manager: it opens the file, gives you f inside the block, and guarantees the file is closed when the block ends β even if an exception is raised. Manual close() calls are easy to skip when an error jumps past them.
Q8. You want a tool that runs as cat log.txt | python3 count.py, with no human present. Which input method fits, and what breaks if you choose input()?
- Use input(); nothing breaks because pipes and keyboards are the same
- Read sys.stdin; input() reads one line and can hang
- Read sys.stdin; input() would print a prompt but still work fine
- Use sys.argv; sys.stdin cannot be read in Python
Show answer
Answer: B. Read sys.stdin; input() reads one line and can hang
A pipeline filter should consume the whole stream with sys.stdin. input() reads a single line and is designed for an interactive human; in an automated context it can block waiting for keyboard input that never comes, so the program appears to hang.
Glossary
- The built-in function that writes its arguments to an output stream (standard output by default), converting each to text and adding a newline; its sep, end, file, and flush arguments control separators, line endings, destination, and buffering.
- input
- The built-in function that reads one line from standard input and returns it as a string with the trailing newline removed; it can display a prompt first, and it always returns text β never a number.
- stdin
- Standard input (file descriptor 0), the stream a program reads from; it may be a keyboard or, in a pipeline, the output of an upstream program.
- stdout
- Standard output (file descriptor 1), the stream a program writes its results to and the channel that feeds the next program in a shell pipeline.
- stderr
- Standard error (file descriptor 2), a second output stream reserved for messages about the run β errors, warnings, progress β kept separate so they do not contaminate the data on standard output.
- f-string
- A formatted string literal, prefixed with f, in which any expression inside curly braces is evaluated and substituted into the text when the program runs; introduced in Python 3.6.
- format spec
- The mini-language written after a colon inside an f-string field, such as >10.2f, controlling fill, alignment, sign, width, thousands separator, precision, and type of the formatted value.
- context manager
- An object used with the with statement that sets up a resource on entry and reliably releases it on exit β closing a file automatically, for example, even if an error is raised inside the block.
- sys.argv
- A list of the command-line arguments passed to a program, as strings; sys.argv[0] is the script name and the real arguments begin at index 1.
- flush
- To force buffered output to be written out immediately rather than held for efficiency; print(..., flush=True) makes text appear the instant it is produced, as in a live progress display.
- prompt
- The text passed to input() and shown to the user before reading their reply, such as input("Your name: ").
- buffer
- A temporary in-memory holding area where output collects before being written out in efficient chunks; flushing empties it early.
- exit code
- An integer a program returns to the shell when it ends; 0 means success and any non-zero value (set with sys.exit(1)) signals failure, letting scripts and pipelines detect problems.
Sources and further reading
- Input and Output β Python Software Foundation (accessed 2026-07-12)
- Built-in Functions β print β Python Software Foundation (accessed 2026-07-12)
- Built-in Functions β input β Python Software Foundation (accessed 2026-07-12)
- Format Specification Mini-Language β Python Software Foundation (accessed 2026-07-12)
- Python String Formatting β Real Python (accessed 2026-07-12)
Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.