input() reads one line of text that the user types, after showing an optional prompt. Whatever they type comes back as a string, so a number must be converted before you can calculate with it:
boxes = int(input("Lunch boxes needed: "))
print("Rice portions:", boxes * 2)That one line covers the happy path. Real users also type three, -2 or nothing at all, and automated runs may have no keyboard. This lesson shows how to write clear prompts, convert text safely, keep asking until the answer is valid, and handle the EOFError that appears when there is no input left. The running example is a community kitchen working out how many lunch boxes to prepare.
Prompt text
The argument to input() is printed as the prompt, without a newline, and the cursor waits right after it. Include a trailing space or colon so the answer doesn't collide with the question:
name = input("Your name: ")
boxes = input("Lunch boxes needed (1-50): ")A good prompt tells the user what kind of answer is expected and, where relevant, the unit or the allowed range. "Quantity?" invites answers such as a dozen or 12 boxes; "Lunch boxes needed (1-50):" makes a plain number the obvious reply. Clear prompts are the cheapest form of validation you'll ever write.
input() reads until the user presses Enter and removes the newline character from the end. It does not remove spaces, so " 12 " comes back with its spaces. Calling .strip() on the result is a common habit: answer = input("Yes or no? ").strip().lower().
Text result
input() always returns a str, even when the user types only digits. That matters as soon as you combine two answers:
first = input("Boxes for Monday: ") # user types 3
second = input("Boxes for Tuesday: ") # user types 4
print(first + second) # 34, two strings joined
print(int(first) + int(second)) # 7+ on strings joins them, so the first print() shows 34. Convert with int() for whole numbers or float() for decimals before doing arithmetic. Check the type when you're unsure: print(type(first)) shows <class 'str'>.
Keep the raw text in its own variable when you need it for an error message, and store the converted value under a clear name, as in raw_count and count. The type casting lesson covers the conversion functions in detail.
Validation
Validating input takes two separate checks:
- Representation: can the text be converted at all?
int("three")raisesValueError. - Business rule: is the converted value acceptable?
int("-2")succeeds, but you can't prepare minus two lunch boxes.
A while True loop with try/except handles both and keeps asking until the answer passes:
while True:
raw = input("Lunch boxes needed (1-50): ").strip()
try:
count = int(raw)
except ValueError:
print(f"{raw!r} is not a whole number.")
continue
if 1 <= count <= 50:
break
print("Please choose between 1 and 50.")The continue jumps back to the prompt after a conversion failure; break leaves the loop only when both checks pass. Error messages should say what was wrong and what is expected, so the user can fix it in one try.
Stream ending
input() reads from standard input. When a person is typing, the line simply waits. When input comes from a file or a pipe, for example python kitchen.py < answers.txt, input() reads one line per call. If no lines are left, or the user presses Ctrl+D (Ctrl+Z then Enter on Windows), it raises EOFError:
try:
count = int(input("Lunch boxes needed: "))
except EOFError:
print("\nNo input received; using the default of 10.")
count = 10Programs that will run unattended, such as scheduled jobs and automated tests, shouldn't depend on input() at all. Pass values as command-line arguments, read them from a file, or use environment variables instead. For many lines of data, read sys.stdin directly: for line in sys.stdin: loops until the input ends without raising an error.
Independent practice and a worked check
Task: ask for a meal preference and a positive count, with a helpful response to invalid numeric text. Accept veg or meat (in any capitalisation) and a count of at least 1.
while True:
meal = input("Meal (veg/meat): ").strip().lower()
if meal in ("veg", "meat"):
break
print("Please type veg or meat.")
while True:
raw = input("How many boxes? ").strip()
try:
count = int(raw)
except ValueError:
print(f"{raw!r} isn't a whole number.")
continue
if count >= 1:
break
print("At least one box, please.")
print(f"{count} {meal} boxes")Test it with VEG, fish, two, 0 and 5 to see every branch. For the worked check, the type input() returns is always str, which is why both answers need processing before they are used.
Reference and next practice
The official input() documentation describes the prompt and EOFError behaviour. Continue with type casting for every conversion function, and see error handling for more on try and except. Then practise with the Python exercises and Python quiz.
User Input with input() Summary
- Prompt text: input displays a prompt and reads one line from standard input.
- Text result: input returns a string even when someone enters only digits.
- Validation: Conversion checks the representation, and range checks enforce the application rule.
- Stream ending: input raises EOFError when no line is available.
User Input with input() Examples
Each example shows the code, the output it produces and what each part does.
User Input with input() in a small program
In the output, 3 is what the user typed after the prompt.
raw_count = input("Lunch boxes needed: ")
count = int(raw_count)
print("Rice portions:", count * 2)Lunch boxes needed: 3
Rice portions: 6Line-by-line explanation
- Line 1The prompt is shown; the typed text
"3"is stored as a string inraw_count. - Line 2
int()converts the text to the number 3. Text like"three"would raiseValueErrorhere. - Line 3Arithmetic now works: 3 boxes need 6 portions of rice.
A reusable input function
Wrapping the retry loop in a function keeps the main program short. In this run the user typed ten, then 0, then 12.
def ask_int(prompt, low, high):
"""Ask until the user enters a whole number from low to high."""
while True:
raw = input(prompt).strip()
try:
value = int(raw)
except ValueError:
print(f" {raw!r} is not a whole number.")
continue
if low <= value <= high:
return value
print(f" Enter a number from {low} to {high}.")
boxes = ask_int("Lunch boxes needed (1-50): ", 1, 50)
print(f"Preparing {boxes} boxes")Lunch boxes needed (1-50): ten
'ten' is not a whole number.
Lunch boxes needed (1-50): 0
Enter a number from 1 to 50.
Lunch boxes needed (1-50): 12
Preparing 12 boxesLine-by-line explanation
- Line 4
.strip()removes accidental spaces before the conversion. - Lines 7 to 9A conversion failure prints a message and
continueasks again. - Lines 10 to 11
returnboth ends the loop and hands back the valid number.
Common User Input with input() Mistakes
Adding two input() results without converting
monday = input("Monday: ")
tuesday = input("Tuesday: ")
print("Total:", monday + tuesday) # 3 and 4 give 34monday = int(input("Monday: "))
tuesday = int(input("Tuesday: "))
print("Total:", monday + tuesday) # 7Both answers are strings, so + joins them. Convert each one before adding.
Accepting any number that converts
count = int(input("Boxes: "))
portions = count * 2 # -4 portions if the user typed -2count = int(input("Boxes: "))
if count < 1:
print("At least one box is needed.")A successful conversion only proves the text was a number. Check the value against your program's rules too.
User Input with input() in Real Projects
input() in real programs
Small command-line utilities, classroom programs and interactive setup scripts use input() to ask a few questions: a project name, a confirmation such as Continue? [y/N], or a menu choice. Passwords use getpass.getpass() from the standard library instead, which hides what is typed.
Larger tools move away from interactive prompts because they can't be automated. They take options with argparse (python kitchen.py --boxes 12), read files, or receive data from web forms. The validation habits from this lesson carry over unchanged: convert the text, check the rule, and give a precise message when either fails.
User Input with input() FAQ
How do I get an integer from input() in Python?
Wrap it in int(): age = int(input("Age: ")). Use float() for decimals. If the user might type something that isn't a number, put the conversion inside try and catch ValueError.
How do I read several numbers from one line of input?
Split the line and convert each part: a, b = map(int, input("Two numbers: ").split()). split() with no argument separates on any spaces. If the user types the wrong number of values, the unpacking raises ValueError.
Why does my program hang waiting at input()?
input() pauses until a line is available. In an editor that runs code without a terminal, or in an automated environment, nobody can type, so the program waits forever or raises EOFError. Run the script from a terminal, or supply the input from a file with python script.py < input.txt.
How do I hide a password while the user types it?
Use the standard library's getpass module: from getpass import getpass, then password = getpass("Password: "). The typed characters are not shown. Some IDE consoles can't hide input and will display a warning instead.
What is the difference between input() and raw_input()?
raw_input() existed in Python 2 and returned a string. Python 2's input() evaluated the typed text as code, which was unsafe. Python 3 removed the old input(), and renamed raw_input() to input(), so in Python 3 input() always returns a string.
User Input with input() Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Which type does input return?
Which review concern is valid for user input with input()?
User Input with input() Quiz
2 questions to check what you learned.
Which type does input return?
- int
- str
- Python ignores the distinction
Which statement correctly describes validation?
- Conversion checks the representation, and range checks enforce the application rule.
- Only the example output matters, not the rule
- Every operation has the same behavior