4.11 Input
Using input() to read from the console, why it always returns a string, converting it to a number, and the standard pattern for validating user input.
input()
What Is It?
Pauses the program, displays an optional prompt, and waits for the user to type a line of text and press Enter.
Why Is It Used?
It’s the standard way to get interactive input from a person running the script.
How Is It Used?
>>> name = input("Enter your name: ")
Enter your name: Alice
>>> name
'Alice'
Type Conversion After input()
What Is It?
input() ALWAYS returns a str, even if the user types a number.
Why Does It Matter?
You must explicitly convert it (int(), float()) before doing arithmetic, or you’ll get a TypeError or unexpected string concatenation instead of addition.
>>> age_str = input("Enter your age: ")
Enter your age: 25
>>> type(age_str)
<class 'str'>
>>> age = int(age_str) # explicit conversion required
>>> age + 1
26
User Interaction
How Is It Used?
Combining input() with validation is the standard pattern for interactive command-line tools:
response = input("Continue? (y/n): ").strip().lower()
if response == "y":
print("Continuing...")
else:
print("Aborted.")
Quick Interview Answer
“
input()displays an optional prompt, blocks until the user types a line and presses Enter, and always returns astr— even if the user typed digits. To do arithmetic on it, you must explicitly convert withint()orfloat()first; skipping that step is the most common beginner mistake withinput().”
Common Mistakes
- Doing arithmetic directly on
input()’s return value without converting it first —input("Age: ") + 1raises aTypeError: can only concatenate str (not "int") to str. - Not calling
.strip()on user input before comparing it — a trailing newline or space from copy-pasted input silently breaks an==comparison.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form