By the end of this lesson, you will be able to capture text from a user via the console and convert it into usable data types like integers or floats.
What it is
In Python, input() is a built-in function that pauses program execution, waits for the user to type something and press Enter, and then returns that typed text as a string. This mechanism allows programs to interact dynamically with users rather than relying solely on hardcoded values. The returned value is always a string, regardless of what the user types (even if they type numbers). To use numeric input, you must explicitly convert the string using functions like int() or float().
Why it matters
- Interactivity: It transforms static scripts into dynamic tools that respond to specific user needs.
- Data Entry: It provides a simple way to collect configuration details, names, or calculations without requiring files or databases.
- Learning Feedback: In educational contexts, it allows immediate testing of logic based on varied inputs.
- Prototyping: It enables rapid development of command-line interfaces (CLI) before building complex GUIs.
Syntax or steps
- Call the
input()function. - Optionally pass a prompt string inside the parentheses to guide the user.
- Assign the result to a variable.
- If numerical data is required, wrap the
input()call inint()orfloat(), or convert the variable afterward.
Example
# Basic string input
name = input("Name? ")
print(f"Hello, {name}!")
# Numeric input with conversion
age_str = input("Age? ")
try:
age = int(age_str)
print(f"You are {age} years old.")
except ValueError:
print("Please enter a valid whole number.")
Explanation:
1. name = input("Name? "): Displays "Name? ", waits for input, and stores the text in name.
2. print(f"Hello, {name}!"): Uses an f-string to insert the variable into the output.
3. age_str = input("Age? "): Captures the age as a string.
4. int(age_str): Attempts to convert the string to an integer. If the user typed "twenty", this raises a ValueError, which we catch to prevent crashing.
Common mistakes
- Assuming automatic type conversion: Users often forget that
input()always returns a string. Adding two inputs directly (input() + input()) concatenates them ("5" + "5" = "55") instead of adding them numerically (5 + 5 = 10). - Lack of error handling: Calling
int(input())without atry/exceptblock will crash the program if the user enters non-numeric characters. - Empty prompts: Using
input()without a prompt argument leaves the user staring at a blank cursor, unsure of what to do. - Trailing whitespace issues: Sometimes users accidentally add spaces. While
int()handles surrounding whitespace, string comparisons might fail unless you use.strip().
When to use it
| Method | Best For | Limitations |
|---|---|---|
input() |
Simple CLI scripts, quick prototypes, single-user local tools. | No validation built-in; blocks execution until Enter is pressed. |
| GUI Libraries (e.g., Tkinter) | User-friendly applications with buttons, forms, and real-time feedback. | Steeper learning curve; requires more code structure. |
Command Line Arguments (sys.argv) |
Automated scripts, batch processing, server-side tasks. | Not interactive; arguments must be known before running. |
Practice
Guided Exercise: Write a script that asks for a user's first name and last name separately, then prints their full name in uppercase.
Challenge: Create a simple calculator that asks for two numbers and an operator (+, -, *, /), then prints the result. Handle division by zero errors.
Hint for Challenge: Use if/elif statements to check the operator string. Wrap the division operation in a try/except ZeroDivisionError block.
Quick check
Question: What is the data type of the value returned by input()?
Answer: It is always a str (string), even if the user types a number.
Summary
The input() function is the primary gateway for human-computer interaction in Python scripts. Remember that it returns strings, so explicit type conversion and error handling are essential for robust programs. Mastering these basics prepares you for more complex data validation and user interface design.