How to take input in Python?
1. Using input()
Function
The input()
function reads a line of text entered by the user and returns it as a string.
Syntax:
variable = input(prompt)
prompt
: An optional string displayed to the user as a message before input.variable
: The variable where the input value is stored.
2. Example: Basic Input
name = input("Enter your name: ")
print(f"Hello, {name}!")
Explanation:
- The prompt
"Enter your name: "
is displayed. - The user types their name and presses Enter.
- The input is stored as a string in the variable
name
. - The program prints a greeting using the entered name.
3. Handling Numeric Input
Since input()
returns a string, you need to convert the input into the desired data type (e.g., int
or float
) if you want to handle numbers.
Example: Taking Integer Input
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
- The
int()
function converts the input string into an integer.
Example: Taking Float Input
height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters.")
- The
float()
function converts the input string into a floating-point number.
4. Input Validation
You should validate user input to ensure the program runs without errors if the user enters unexpected data.
Example: Handling Errors with try
and except
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
except ValueError:
print("Invalid input! Please enter a number.")
- If the user enters non-numeric data, the program will catch the error and display a friendly message.
5. Taking Multiple Inputs
You can take multiple inputs on the same line or process multiple inputs efficiently.
Example: Multiple Inputs in a Single Line
x, y = input("Enter two numbers separated by space: ").split()
x = int(x)
y = int(y)
print(f"The sum is {x + y}")
- The
split()
method separates the input string into parts based on spaces by default.
Example: Using List Comprehension
numbers = [int(x) for x in input("Enter numbers separated by space: ").split()]
print(f"The numbers are: {numbers}")
6. Input Without Prompt
If you don’t provide a prompt, the user can still enter data, but the program won’t display any specific message.
Example:
data = input()
print(f"You entered: {data}")
7. Advanced Techniques
- Default Values: Provide default values if the user enters nothing.
data = input("Enter something (or press Enter to skip): ") or "default"
print(f"You entered: {data}")
- Stripping Extra Whitespace: Remove leading/trailing whitespace using
.strip()
.
data = input("Enter something: ").strip()
print(f"You entered: {data}")
Summary
- Use
input()
to read data from the user. - Convert the input to other types using
int()
,float()
, etc., when needed. - Validate user input and handle any unwanted entries.
- Use advanced techniques such as splitting or stripping to make it usable.