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.
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? ")
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.
input(): input("Age: ") + 1 raises TypeError because input() returns a string; convert with int() or float().choice.strip().lower() == "y" instead of choice == "y".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.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.
Call parts = input("Scores: ").split(), then convert each item with [int(x) for x in parts].
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.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.