Input & output
print() options, reading and validating input(), stdout vs stderr, sys.argv, argparse and exit codes.
A program that can't talk to the outside world isn't much use. In this lesson you'll learn the three basic channels a script uses: printing output, reading what the user types, and accepting command-line arguments. Along the way you'll meet standard error and exit codes, which matter as soon as your scripts are used by other people or other programs.
print() in depth#
You've used print already. It has a few keyword arguments worth knowing:
print converts every argument with str(), so you can pass numbers, lists or None directly. For anything more complex than a couple of values, reach for an f-string.
Printing a whole list one item per line is a neat trick with unpacking:
Reading input with input()#
input(prompt) shows the prompt, waits for the user to press Enter, and returns what they typed as a string (without the newline):
(In the output above, Ada is what the user typed.)
Converting input
Because input always returns str, doing maths on it needs a conversion:
If the user types twenty, int() raises ValueError and the program crashes. A robust program keeps asking until it gets valid input. You'll learn try/except fully later, but the pattern is simple enough to use now:
Reading several values from one line is a common need in coding exercises:
Always tidy user input with .strip() (and often .lower()) before comparing it: if answer.strip().lower() in ("y", "yes"):.
Standard output vs standard error#
Every program has two output streams: stdout for normal results and stderr for errors and diagnostics. Keeping them separate lets users redirect results to a file while still seeing errors on screen.
Command-line arguments#
Scripts that run in terminals, cron jobs and CI pipelines take their input from the command line instead of input(). The raw arguments are in sys.argv:
For anything beyond one or two arguments, use the standard library's argparse, which gives you parsing, type conversion, defaults and a free --help page:
Running python3 greet_cli.py --help prints an automatically generated usage page, and a wrong value (like --times abc) produces a helpful error instead of a traceback.
Exit codes#
When a program finishes, it returns an exit code to whoever started it: 0 means success, anything else means failure. Shell scripts and CI systems check it. Use sys.exit() to set it:
Worked example: a tip calculator#
Putting it together — an interactive script with validated input and formatted output:
Common mistakes#
- Forgetting to convert input.
input("n: ") * 2repeats the text; it doesn't double the number. - Not stripping input. A stray space makes
"yes " == "yes"false. - Printing errors to stdout. Use
file=sys.stderrso errors don't pollute redirected output. - Using
input()in scripts meant for automation. Cron jobs and CI have no keyboard; take arguments withargparseinstead.
What's next#
Your programs can now talk to users. Next, let's teach them to make decisions with conditionals: if, elif, else and the match statement.
Check your understanding
Quick quiz
1.What type does
input()always return?2.What does
print("a", "b", sep="-", end="!")output?3.In
python3 app.py report.csv, what issys.argv[1]?
Finished reading?
Mark this lesson complete to track your progress.