Sub topic 3
Reading input with input()
This chapter assumes you can run a Python script and know the basic types str, int and float. It also assumes you are comfortable with try and except. You have already used print() to write output. Now you will read text the user types.
How input() works
input() is a built-in function that pauses the program, waits for the user to type a line and press Enter, and returns what they typed. The optional argument is a prompt, which is printed first without a trailing newline.
name = input("Your name: ")
print(f"Hello, {name}!")The returned string does not include the newline that Enter produced. If the user presses Enter without typing anything, input() returns an empty string, "".
The result is always a string
input() returns a str, even when the user types digits. This causes the most common beginner bug:
a = input("First: ")
b = input("Second: ")
print(a + b)If the user enters 2 and then 3, the output is 23, because + joins two strings. The next chapter covers converting to numbers. For now, remember that anything you read starts as text.
Cleaning up what you read
Users add stray spaces and vary their capitalization. Because the result is a string, you can use string methods straight away.
answer = input("Continue? (y/n): ").strip().lower()
if answer == "y":
print("Continuing.")
elif answer == "n":
print("Stopping.")
else:
print(f"Unrecognized answer: {answer!r}")strip() removes leading and trailing whitespace, and lower() makes the comparison case-insensitive. Printing the unrecognized value with !r shows hidden spaces, which helps when you debug.
When input ends or is interrupted
input() can raise two exceptions that you should know about.
| Exception | Cause | Typical trigger |
|---|---|---|
| `EOFError` | No more input is available | Ctrl+D on Linux/macOS, Ctrl+Z then Enter on Windows, or a script run with empty piped input |
| `KeyboardInterrupt` | The user interrupted the program | Ctrl+C |
An interactive script usually lets KeyboardInterrupt end the program. EOFError is worth handling when your script might run non-interactively:
try:
line = input("Command: ")
except EOFError:
line = ""
print("No more input.")
print(f"Got: {line!r}")Common errors
- Using the result as a number.
input("Age: ") + 1raisesTypeError, because you cannot add anintto astr. - Forgetting the space in the prompt.
input("Name:")leaves the cursor touching the colon. End the prompt with a space. - Comparing without cleaning.
"Y "does not equal"y". Usestrip()andlower()first. - Expecting a prompt when output is redirected. The prompt still goes to stdout, so it can end up in a redirected file.
Exercise
A script runs x = input("Number: ") and print(x * 2). The user types 4. What is printed, and why?
Show answer
It prints 44. input() returns the string "4", and multiplying a string by 2 repeats it. The value is never treated as a number until you convert it.