The built-in input(prompt) function reads a line from interactive terminal input as a string. Robust command-line tools require input sanitization, type validation, and signal handling.
flowchart TD
A["input(prompt) Call"] --> B["Pause & Wait for User Keypresses"]
B --> C["User Presses Enter (
)"]
C --> D["Return Input as String (str)"]
D --> E["Sanitize (.strip()) & Cast Type (int/float)"]
E --> F{"Validation Successful?"}
F -- "Yes" --> G["Proceed with Command"]
F -- "No" --> H["Print Error & Re-prompt Loop"]
import sys
from typing import Optional
def prompt_positive_integer(prompt_msg: str, max_retries: int = 3) -> Optional[int]:
"""Prompt user for a positive integer with input validation and retry limits."""
attempts = 0
while attempts < max_retries:
try:
raw_input = input(prompt_msg).strip()
val = int(raw_input)
if val <= 0:
print("Error: Input must be a positive integer (> 0).")
attempts += 1
continue
return val
except ValueError:
print("Error: Invalid numeric input. Please enter a valid integer.")
attempts += 1
except (KeyboardInterrupt, EOFError):
print("
User cancelled input prompt.")
sys.exit(0)
print("Maximum retry limits reached.")
return None
if __name__ == "__main__":
# Simulated automated execution check
if not sys.stdin.isatty():
print("Non-interactive environment detected; skipping live terminal prompt.")
else:
age = prompt_positive_integer("Enter your age: ")
print(f"Validated Age: {age}")
input() Always Returns str: input("Enter number: ") returns a string "42", not an integer 42. You must explicitly cast int(input(...)).KeyboardInterrupt & EOFError: Always handle Ctrl+C (KeyboardInterrupt) or EOF signals cleanly when building CLI interfaces..strip() on raw terminal inputs to remove trailing newlines and whitespace.Write a loop that prompts the user for their email address until a valid email containing both @ and . is provided.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With