input() writes its prompt argument, if given, to standard output without a trailing newline, then blocks until the user types something and presses Enter, stripping the trailing newline from what they typed and returning the result always as a string, even if the user typed digits. That's why numeric input needs an explicit conversion, and why that conversion can raise ValueError if the text isn't a valid number.
1Understanding input()
input() writes its prompt argument, if given, to standard output without a trailing newline, then blocks until the user types something and presses Enter, stripping the trailing newline from what they typed and returning the result always as a string, even if the user typed digits. That's why numeric input needs an explicit conversion, and why that conversion can raise ValueError if the text isn't a valid number.
Always wrap a numeric conversion of input() in a try/except ValueError block — real users will eventually type something that isn't a number.
name = input("What is your name? ")
print(f"Hello, {name}!")2Practical Example
Here is a real-world application of input() showing how it is used in production Python code.
while True:
text = input("Enter your age: ")
if text.isdigit():
age = int(text)
break
print("Please enter digits only.")
print(f"You are {age} years old.")3Best Practices
Follow these guidelines when working with input():
1. Convert input() with int() or float() explicitly when you need a number — it's always a string otherwise
2. Validate input in a loop, asking again, rather than crashing on the first bad entry
3. Avoid using input() in automated/non-interactive scripts, like web servers — it will hang waiting for a terminal that isn't there
Tip: Always wrap a numeric conversion of input() in a try/except ValueError block — real users will eventually type something that isn't a number.
name = input("What is your name? ")
print(f"Hello, {name}!")