Python User Input
Python User Input: Reading and Validating Terminal Prompts
Python's built-in input() function pauses your script, displays an optional prompt, and waits until the user types a line and presses Enter. Regardless of what the user types, input() always returns a string (str).
Because terminal users often type extra spaces or non-numeric characters, real CLI scripts trim and validate input inside a loop before using it.
Reading, Cleaning, and Validating Input
Strip leading and trailing whitespace with .strip(), and convert numbers inside a try ... except ValueError loop so bad input re-prompts cleanly.
def ask_positive_int(prompt: str) -> int:
while True:
raw = input(prompt).strip()
try:
value = int(raw)
if value > 0:
return value
print("Please enter a number greater than 0.")
except ValueError:
print("That was not a valid whole number. Try again.")
# Example usage in a terminal script:
# seats = ask_positive_int("How many seats? ")
Reading Secret Passwords Without Echoing
Never use input() for passwords or API keys because characters appear on the screen. Import getpass.getpass("Password: ") from the standard library to hide typed characters automatically.
Common Mistakes to Avoid
- Doing math directly on
input():input("Age: ") + 1raisesTypeErrorbecauseinput()returns a string; convert withint()orfloat(). - Trusting case or spacing: Compare normalized text like
choice.strip().lower() == "y"instead ofchoice == "y". - Using
input()inside automated server endpoints:input()blocks waiting for standard input (stdin); web apps and background jobs must use command-line arguments (argparse) or HTTP request bodies.
Frequently Asked Questions
Does input() work differently in Python 2 vs Python 3?
Yes. Python 3 input() safely returns a raw string. Python 2 input() evaluated code and caused security holes, which is why Python 3 removed it.
How do I accept multiple space-separated numbers on one line?
Call parts = input("Scores: ").split(), then convert each item with [int(x) for x in parts].
What happens if the user presses Ctrl+D or Ctrl+C at an input() prompt?
Python raises EOFError on end-of-file (Ctrl+D) and KeyboardInterrupt on Ctrl+C, both of which you can catch cleanly to exit.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.