Sub topic 3
Reading input with input()
This chapter covers how input() behaves: what it returns, what it strips, how it ends, and where it can fail. It assumes you can run a Python script and know the basic types str, int, and float. It also assumes you know if statements, while loops, and basic try/except. Converting the text to numbers and validating it each get their own chapter, so here you only see the strings.
What input() does
input() pauses the program, waits for the user to type a line and press Enter, and returns that line as a string.
name = input("Your name: ")
print("Hello,", name + "!")Running it looks like this:
Your name: Ada
Hello, Ada!The call takes one optional argument, the prompt. Python writes the prompt to standard output without a trailing newline, so the cursor stays on the same line. Before it waits for input, Python flushes standard output. The prompt therefore appears even when output is buffered. Without a prompt, the program waits silently, which looks like a hang to the user.
The sequence below shows who does what in one call.
The result is always a string
Whatever the user types, you get a str. Digits are still characters.
value = input("Enter a number: ")
print(type(value))
print(value + value)If the user types 12, the output is:
<class 'str'>
1212The + operator concatenates strings, so "12" + "12" is "1212", not 24. This is the most common beginner bug with input(). The fix is conversion, which the next chapter covers.
The trailing newline that Enter produces is removed for you. Everything else is kept, including leading and trailing spaces.
Edge cases in what you get back
Three details are worth knowing, because each causes bugs in programs that look correct.
- Empty input. If the user presses Enter immediately,
input()returns"". An empty string is falsy, soif not answer:is a clean way to detect it. - Surrounding whitespace. A user who types
" yes "gives you" yes ". Compare against the raw value and you will reject a sensible answer. - Case.
"Y","y", and"YES"are different strings.
Normalize before comparing. str.strip() removes whitespace from both ends. str.casefold() is a stricter, Unicode-aware version of lower() meant for comparisons.
answer = input("Continue? [y/N] ").strip().casefold()
if answer in ("y", "yes"):
print("Continuing.")
else:
print("Stopping.")Treating an empty answer as "no" matches the capital N in the prompt, a common convention for marking the default.
Several values on one line
input() reads a whole line. If you want several values, split the line yourself. str.split() with no argument splits on any run of whitespace and ignores leading and trailing whitespace.
line = input("Type some words: ")
parts = line.split()
print(parts)
print(len(parts), "words")Typing red green blue prints ['red', 'green', 'blue'] and 3 words. Unpacking such a list directly, as in first, second = line.split(), raises ValueError if the user types a different number of words. Check len(parts) first, or catch the exception.
When input() raises exceptions
Two exceptions are part of normal operation, and a script that reads input should plan for them.
| Exception | Cause | Typical response |
|---|---|---|
| `EOFError` | No more input: the user pressed Ctrl-D (Unix) or Ctrl-Z then Enter (Windows), or piped input ran out | Stop reading, or fall back to a default |
| `KeyboardInterrupt` | The user pressed Ctrl-C | Usually let it end the program, or clean up first |
EOFError matters most when input is not typed by a person. A script run as python app.py < data.txt or at the end of a pipe reaches end of input and then raises EOFError on the next input() call. That is also how you read all the lines of a redirected file:
lines = []
while True:
try:
line = input()
except EOFError:
break
lines.append(line)
print("Read", len(lines), "lines")Save this as count_lines.py and run it with piped data:
printf 'alpha\nbeta\ngamma\n' | python count_lines.pyIt prints Read 3 lines. Here input() has no prompt, so nothing extra is written to the output, which keeps it clean for other programs that consume it.
input() versus sys.stdin
input() is a convenience over the standard input stream, which a later chapter covers in full. You can read the same stream directly with sys.stdin.readline(). The two differ in ways that matter for edge cases.
import sys
line = sys.stdin.readline()
print(repr(line))If the input is hello followed by Enter, this prints 'hello\n'. The newline is kept. At end of input, readline() returns '' instead of raising an exception. input() returns 'hello' and raises EOFError at the end.
| Behavior | `input()` | `sys.stdin.readline()` |
|---|---|---|
| Trailing newline | Removed | Kept |
| At end of input | Raises `EOFError` | Returns `""` |
| Prompt | Optional, written to stdout | None |
| Line editing and history | Available in a terminal if the `readline` module is loaded | Not available |
For interactive programs, use input(). For code that processes a stream of lines, such as a filter in a shell pipeline, iterating over sys.stdin (for line in sys.stdin:) is often cleaner than a while True loop with EOFError.
Prompts: small details that matter
A prompt is just a string, so you can build it like any other string. Two habits make prompts easier to use.
- End the prompt with a space or a colon and a space, such as
"Age: ". Otherwise the typed text runs into the prompt. - Show the expected format, the default, or the valid choices, as in
"Date (YYYY-MM-DD): "or"Delete file? [y/N] ".
For a multi-line prompt, include \n in the string. The cursor then waits at the end of the last line:
choice = input("1) Start\n2) Quit\nChoose: ")
print("You chose", repr(choice))Printing repr(choice) shows the quotes and any stray whitespace the user typed, which helps when debugging comparisons that fail unexpectedly.
Secrets: getpass
input() echoes what the user types. For passwords and tokens, use getpass.getpass() from the standard library. It disables echo and otherwise works like input().
from getpass import getpass
secret = getpass("Password: ")
print("Received", len(secret), "characters")Print only the length, never the secret itself. Note that getpass reads from the terminal, not from standard input, so piped input will not feed it. That is intentional: it keeps secrets out of shell history and scripts.
Testing code that calls input()
Interactive code is awkward to test, so keep the reading separate from the logic. Put the decision in a function that takes a string, and call input() only in a thin outer layer.
def is_yes(text):
return text.strip().casefold() in ("y", "yes")
if __name__ == "__main__":
print("Proceeding." if is_yes(input("Proceed? ")) else "Cancelled.")is_yes can now be tested with plain strings such as " YES " and "", without simulating a keyboard. You can still check the full script from the shell with echo y | python script.py.
Common mistakes
- Treating the result as a number.
input()returns text. Do not compare it to anintor add it to one until you convert it. - Forgetting to normalize. Strip whitespace and fold case before comparing against fixed answers.
- Ignoring
EOFErrorin scripts that may run with redirected input. - Printing the prompt with
print()and then callinginput()with no prompt. This works, but the prompt then ends with a newline, and flushing behavior is easier to get wrong. Pass the prompt toinput()instead.
Exercise
A script runs answer = input("Save? [Y/n] "). Write the line that makes answer a normalized string, then write a condition that is true for the inputs "y", " YES ", and an empty line (the default is yes), but false for "n" and "No". What exception can input() raise if the script is run as python save.py < empty.txt where empty.txt has no content?
Show answer
Normalize with answer = input("Save? [Y/n] ").strip().casefold(). The condition is answer in ("", "y", "yes"). For "y", " YES " and an empty line this is true. For "n" and "no" it is false. With an empty redirected file there is no line to read, so input() raises EOFError.