Input, Variables, and Enumeration Related Tips

Let input() speak for itself

There are many questions we must ask when a console-based program suddenly stops. Why? Did it hang up? Is it busy? Is it waiting for the input? If so, for what is it waiting? As a programmer, we can eliminate most of these questions by providing prompts.

A prompt is a printed invitation to enter some missing information. We should display a prompt just before the program stops and wait for user input (presumably by calling the input() function). 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.

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

year = input('Enter year of birth: ')

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

Remember that the prompt is merely a string. It can be a constant and can be pre-calculated. It can also be calculated during the call to personalize the invitation or configure it in any other way:

name = input('Enter your name: ').strip()
year = input(f'What is your year of birth, {name}? ')

Get hands-on with 1400+ tech skills courses.