This guide explains input() Function: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
input(prompt) displays an optional prompt, waits for a line of user input, and returns that text without the trailing newline. The returned value is always a string, even if the user types digits.
When You Would Use This
An interactive greeting asks for a first name and makes the response more personal.
Step-by-Step Example
entered_name = input("First name: ").strip()
if entered_name:
print(f"Welcome, {entered_name}!")
else:
print("No name was entered.")
How the Example Works
The input text is stripped of leading and trailing whitespace. The condition tests whether anything remains. Run this script in an interactive terminal and type a name when prompted.
Try It Yourself
Change the prompt to ask for a city and show a different message for empty answers.
Common Beginner Mistakes
- Treating the returned string as an integer without conversion.
- Assuming an empty answer is impossible.
- Testing interactive input in a non-interactive environment and misreading an
EOFErroras a syntax error.
Key Takeaways
input(prompt)displays an optional prompt, waits for a line of user input, and returns that text without the trailing newline.- The input text is stripped of leading and trailing whitespace.
- Avoid this mistake: Treating the returned string as an integer without conversion.