input() with a Prompt
Your program now waits for the user. But it waits in complete silence — a blank screen and a blinking cursor, with no clue what it wants. One small addition fixes that, and it goes inside the brackets.
1The problem: a program that waits in silence
Run the program from the last lesson and put yourself in the shoes of someone who has never seen the code:
a = int(input())
b = int(input())
print('The sum is', a + b)▮
That is the entire screen. A cursor, blinking. How many numbers does it want? Two? Ten? Should you type a name? Is the program stuck, or is it waiting for you? The user has no way of knowing, because nobody told them.
You could print a message on the line before, and that does work perfectly well:
print('Enter the first number:')
a = int(input())But this is so common that input() will do it for you — and it looks tidier on screen.
2Put the message inside the brackets
Anything you write inside the brackets of input() is shown to the user just before the program stops to wait. That message is called the prompt:
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
print('The sum is', a + b)Enter the first number: 10 Enter the second number: 5 The sum is 15
Same program, same answer — but now anybody can use it without seeing the code. Try it below, and change the prompts to whatever you like:
input(). Python shows it, then waits. It changes nothing about what input() returns — you still get text, and you still need int() or float() to do maths with it.3The little detail: end the prompt with a space
The user types immediately after your message, on the same line. So if your prompt ends flush against the last letter, their answer collides with it:
The only difference is a single space before the closing quote. It costs nothing and it is what separates a program that looks finished from one that looks half-done.
'Enter: ' but 'Enter your marks out of 100: '. If the value has units or a format, say so — 'Height in metres: ' saves everybody a wrong answer.4Your turn
Here is a program with no prompts at all. Add one to each input() so that somebody who has never seen the code could still use it:
Notice that name has no int() or float() around it. A name is text, so the text that input() hands back is exactly what we want. You only convert when you need to do maths.
5Recap
input('Enter your age: ') — and Python shows it before waiting. End it with a space so the user's typing does not run into your words. The prompt is only a message: the value still comes back as text, so int() and float() are still needed for numbers.What does the message inside the brackets of input() do?
After age = input('Enter your age: ') the user types 25. What is in age?
Which line makes for the most readable screen?