By now, you're familiar with Python's input()
function. But today, we’ll take it up a notch and learn how to make it smarter, safer, and more user-friendly.
Let’s explore:
- Type conversion
- Error handling
- Custom prompts
- Looping until valid input
- Handling lists, multiple values, and booleans
🧠 The Basics of input()
name = input("Enter your name: ")
print(f"Hello, {name}!")
But here’s the catch — input()
always returns a string.
So for numbers and other types, you must convert it manually.
🔁 Converting Input to Numbers
age = int(input("Enter your age: "))
print(f"You will be {age + 1} next year.")
If the user enters something invalid (like "hello"), this throws an error.
🛡️ Safe Input with try-except
Let’s make it safer:
try:
age = int(input("Enter your age: "))
print(f"You entered: {age}")
except ValueError:
print("That's not a valid number!")
🔄 Loop Until Valid Input
Use a loop to ask repeatedly until correct input is given:
while True:
user_input = input("Enter a number: ")
try:
number = float(user_input)
break
except ValueError:
print("Please enter a valid number!")
🔢 Getting Multiple Inputs
Split input with .split()
:
data = input("Enter your name and age (e.g., John 25): ")
name, age = data.split()
print(f"Name: {name}, Age: {age}")
To convert age:
age = int(age)
Or using list comprehension:
nums = input("Enter 3 numbers separated by space: ")
numbers = [int(x) for x in nums.split()]
print(numbers)
✅ Accepting Boolean Input
For yes/no or true/false, use .lower()
and compare:
ans = input("Do you agree? (yes/no): ").strip().lower()
if ans in ["yes", "y"]:
print("Agreed!")
elif ans in ["no", "n"]:
print("Not agreed.")
else:
print("Invalid response.")
🛠️ Creating Custom Input Functions
You can wrap all of this in reusable functions:
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a valid integer.")
age = get_int("Enter your age: ")
print(age)
📦 Parsing JSON from Input
import json
data = input("Enter JSON: ")
try:
obj = json.loads(data)
print("Parsed:", obj)
except json.JSONDecodeError:
print("Invalid JSON")
🧪 Extra: Input with Defaults
Python doesn't natively support defaults with input()
, but you can simulate:
def input_with_default(prompt, default="yes"):
user_input = input(f"{prompt} [{default}]: ")
return user_input.strip() or default
response = input_with_default("Continue?")
print(response)
🧾 Summary
Task | Solution Example |
---|---|
Basic input | input("Enter name: ") |
Convert to number | int(input(...)) |
Safe input (try-except) | Use try-except for validation |
Loop until valid |
while True with break
|
Split multiple inputs | input().split() |
List of values | [int(x) for x in input().split()] |
Boolean input | Check for "yes"/"no" variants |
JSON parsing | Use json.loads()
|
Input with default fallback | Simulate with string check |
✅ TL;DR
-
input()
always returns strings — convert and validate! - Wrap your logic in reusable functions for cleaner code.
- Use loops +
try-except
for bulletproof input handling. - Make your scripts interactive and user-proof.