Tip 9 Let input() Speak for Itself

Pythonic Programming — by Dmitry Zinoviev (17 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Do Not Misuse Docstrings | TOC | Mark Dummy Variables 👉

★3.4+ There is little that is more embarrassing than a console-based program that suddenly stops and shows no signs of life. Why??? Did it hang up? Is it busy? Is it waiting for your input? If so, for what is it waiting? As a programmer, you can eliminate most of these questions by providing prompts.

A prompt is a printed invitation to enter some missing information. You should display a prompt just before the program stops and waits for user input (presumably by calling the function input). The prompt should explain concisely, in a language suitable to the expected user, what the user should input and how. It is customary, but not required, for a prompt to end with a colon and space.

You can use function print to display the prompt, followed by input to collect the input. A better solution is to let input speak for itself; if you pass an argument to input, the argument will be printed just before the function stops:

​ year = input(​'Enter year of birth: '​)​=> ​Enter year of birth: 2048​

Keeping the prompt and the collector together self-documents the collector’s purpose and reminds the user what input is expected, especially if the program needs more than one input.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.