Programming with Python β€Ί Python Setup and First Programs β€Ί Day 47

Day 47: Input, Output, and f-strings

Day 47 of 365 β€” 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.

Course
Programming with Python
Category
Python Setup and First Programs
Reading time
β‰ˆ 40 min
Practical time
β‰ˆ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

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

  1. 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
  2. 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
  3. 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.
  4. 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:

Prerequisites

Why this matters


The idea in plain language

Diagram: what belongs on stdout compared with stderr


Historical background


What it is β€” and what it is not

These streams are:

They are not:


Why it was created and what problems it solves


How it works

The three streams

Diagram: how the shell redirects a program's three streams

Diagram: a Python program's three standard streams β€” stdin in, stdout and stderr out β€” and how they connect in a shell pipeline

Diagram: line buffering to a terminal compared with block buffering to a pipe

print("a", "b", sep="-", end="")   # a-b, with no newline
print("progress", file=sys.stderr, flush=True)

input(), and the trap

Diagram: why input returns text and what to do about it

age = input("Age: ")        # always a str, even for "42"
age = int(input("Age: "))   # raises ValueError on "abc"

f-strings for output

Diagram: the f-string format specification broken into fill/align, width, precision, and type fields

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

Files, and why with

Diagram: opening a file with a context manager compared with closing it manually

with open("data.csv", encoding="utf-8") as f:
    for line in f:
        ...

Command-line arguments

Diagram: how sys.argv maps to shell positional parameters

import sys
target = sys.argv[1] if len(sys.argv) > 1 else "."

An everyday analogy

A machine on a factory line.

The lineThe program
The input hopperstdin
The output chutestdout
The reject chutestderr
The settings dialCommand-line arguments
Asking an operator a questioninput()
The machine not caring what comes nextRedirection
Closing the hatch when you leavewith

Examples in practice

Diagram: iterating a file line by line compared with reading it entirely


Implications: security, privacy, performance, scalability, and cost

Diagram: opening a file with and without an explicit encoding


Alternatives: free, open source, and commercial

Diagram: print compared with the logging module

ToolTypeWhere it fits
print / inputFree, built inEverything simple
sys.stdout.writeFree, built inWhen you want no automatic newline at all
argparseFree, standard libraryReal command-line interfaces β€” Day 80
getpassFree, standard libraryReading a secret without echoing it
pathlibFree, standard libraryPaths, and Path.read_text() for small files
loggingFree, standard libraryAnything long-running; levels and destinations

TermWhat it actually is
stdinThe stream a program reads from
stdoutWhere its results go
stderrWhere its commentary goes
BufferingHolding output until there is enough to write
flushForcing the buffer out now
Context managerThe object with sets up and tears down
sys.argvThe command line, as a list of strings

When to use it β€” and when not to


The AI connection

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 doingCommand
Write to both streamsprint("data") and print("note", file=sys.stderr)
Prove the pipe carries onepython3 s.py | wc -l
Send errors to a filepython3 s.py 2> errors.txt
See the input trapint(input()) with abc typed
Format numbersf"{0.03174:.4f}", f"{0.914:.1%}", f"{1234567:,}"
Read a file safelywith open(p, encoding="utf-8") as f:
Take an argumentsys.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

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. A learner writes total = input("a: ") + input("b: "), types 5 then 7, and finds total is "57". What happened?

  1. input() returned numbers, but + concatenated them by mistake
  2. Python added 5 and 7 but displayed the result in a different base
  3. input() always returns a string, so + joined "5" and "7" instead of adding
  4. 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?

  1. end
  2. sep
  3. file
  4. 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?

  1. Right-aligns it in a field 10 characters wide with exactly 2 decimal places
  2. Left-aligns it in 10 characters with 2 significant figures
  3. Pads it with 10 zeros and rounds to 2 decimals
  4. 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?

  1. Standard error is faster than standard output
  2. Errors on standard output would flow down the pipe
  3. Standard output cannot display red text
  4. 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?

  1. The first real argument, "Ada"
  2. The number of arguments, 2
  3. The script name, "greet.py"
  4. 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?

  1. eval() is slower than int()
  2. eval() rounds numbers incorrectly
  3. eval() only works on numbers, not text
  4. 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?

  1. with open("out.txt", "w") as f:
  2. f = open("out.txt", "w") and remember to call f.close() at the end
  3. open("out.txt", "w").write(...) on one line
  4. 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()?

  1. Use input(); nothing breaks because pipes and keyboards are the same
  2. Read sys.stdin; input() reads one line and can hang
  3. Read sys.stdin; input() would print a prompt but still work fine
  4. 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

print
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


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.