The input() Function – Basics
The input() function pauses your program, displays a prompt, waits for the user to type something and press Enter, then returns what they typed as a string.
# Basic input
name = input("What is your name? ")
print(f"Hello, {name}!")
Always Returns a String – Type Conversion Required
This is the most common mistake: input() ALWAYS returns a string, even if the user types a number. You must convert it to the right type.
# ❌ Bug: comparing string to integer
age = input("Enter your age: ") # Returns "25" (string)
if age > 18: # Error! Can't compare str > int
print("Adult")
# ✅ Correct: convert to int first
age = int(input("Enter your age: ")) # Now it's an integer
if age > 18:
print("Adult")
Converting Input to Different Types
Use int(), float(), or other conversion functions wrapped around input() to get the type you need.
name = input("Name: ") # str - no conversion needed
age = int(input("Age: ")) # int
price = float(input("Price: $")) # float
active = input("Active? (y/n): ") == "y" # bool
print(type(name), type(age), type(price), type(active))
Input Validation – Handling Bad Input
Users type unexpected things. Always validate input when your program depends on a specific format.
# Keep asking until valid number given
while True:
try:
age = int(input("Enter age (0-120): "))
if 0 <= age <= 120:
break
print("Age must be between 0 and 120.")
except ValueError:
print("Please enter a valid number.")
print(f"Your age is: {age}")
Getting Multiple Inputs
You can get multiple values in one line using split(), or ask separately.
# Option 1: separate inputs
first = input("First name: ")
last = input("Last name: ")
# Option 2: one line, split by space
x, y = input("Enter two numbers (space-separated): ").split()
x, y = int(x), int(y)
print(f"Sum: {x + y}")
Reading Input Safely
input() pauses the program, waits for the user to type a line, and returns it as a string (the newline stripped). Everything about robust input handling flows from that one fact.
name = input("Your name: ") # str
qty = int(input("How many? ")) # convert numbers explicitly
# robust: don't crash on bad input
while True:
try:
age = int(input("Age: "))
break
except ValueError:
print("Please enter a whole number.")
| Task | Pattern |
|---|---|
| a number | int(input(...)) |
| several values on one line | input().split() |
| validate | try/except ValueError loop |
The core gotcha (again): input is always text, so numeric input needs casting before math. Robustness: real programs never trust the user — wrap conversions in try/except so a typo shows a friendly message instead of a traceback. To read several values at once: a, b = input().split(), then cast each. For scripts that take arguments instead of interactive prompts, use sys.argv or the argparse module — cleaner for tools that run non-interactively.
🏋️ Practical Exercise
Build an interactive prompt:
- Ask the user for their name with
input()and greet them. - Ask for their birth year, convert it to an int, and print their approximate age.
- Read two numbers on one line using
split()and print their sum. - Re-prompt the user until they enter a valid number, using a loop and
try/except.
🔥 Challenge Exercise
Create a simple guess-the-number game. Pick a secret number, then repeatedly use input() to read guesses. Convert each guess to an int inside a try/except so bad input is rejected gracefully, tell the player “higher” or “lower”, and count attempts until they guess correctly. Bonus: limit the player to a maximum number of tries.
📋 Summary
input(prompt)displays an optional prompt and reads one line from the user.input()always returns a string, even when the user types digits.- Convert input explicitly with
int()orfloat()before doing arithmetic. - Use
.split()to read several values from a single line. - Wrap conversions in
try/except ValueErrorand loop to re-prompt on invalid input. - In Python 3,
input()replaced Python 2’sraw_input().
Interview Questions on User Input
- What does the
input()function return, and what type is it? - How do you read a number from the user?
- How do you read multiple values from a single line of input?
- How do you validate user input and re-prompt on errors?
- What is the difference between
input()in Python 3 andraw_input()in Python 2? - How do you handle a
ValueErrorfrom a bad numeric input? - How do you provide a prompt message with
input()?
Related Topics
FAQ
input() return a string even when I type a number? +By design, input() reads raw text and never guesses the type. To do math you must convert it yourself with int() or float(), which also gives you a clear place to validate the value.
Read the line, then split it: a, b = input().split() gives two strings, which you convert. A common idiom is nums = list(map(int, input().split())) to get a list of integers.
Put the input() and conversion inside a while True loop wrapped in try/except ValueError. On success, break; on failure, print a message and let the loop prompt again.
raw_input() from Python 2? +Python 3’s input() behaves like Python 2’s raw_input() — it returns a string. Python 2’s old input() (which evaluated the text as code) was removed for safety.

