The Python input() function reads whatever the user types at the keyboard. The catch every beginner trips on: it always hands you a string. This guide shows the type casting and validation patterns that turn that raw text into safe integers, floats, and yes/no answers without your program crashing.
“Never trust user input. Never.”
OWASP Foundation
Last Updated: July 2026 | Tested on: Python 3.14.6 | Difficulty: Beginner | Reading Time: 12 minutes
So far your programs have only talked one way. You write the values, Python prints the results, and the user just watches. Real programs hold a conversation. The user types something, the program answers, the user types again. That back and forth runs through the Python input function, input().
Here is the trap that catches everyone on day one. The Python input() function always returns a string. Always. Even when the user types 42, Python hands you the text "42", not the number 42. Think of it like a cashier reading a price tag out loud. The words “forty two” are not money you can add up, they are just a label you heard. You have to convert that label into a real number before you can do any math with it. Forget this one detail and you get a surprise TypeError the moment you try to do math with it.
Table of Contents
Basic input()
The diagram traces how the Python input() function works. The function shows a prompt, waits for the user to type, captures the answer as a string, and then (optionally) runs it through type casting like int() or float(). The one detail that matters most: input() always returns a string. Skip the conversion step and arithmetic on user input will glue the text together instead of adding the numbers. Every code example below walks one branch of this flow.
Think of input() as a receptionist with a notebook. Whatever a visitor says, the receptionist writes it down as words, even if the visitor says a number. Run the script below and picture a user named Rahul sitting at the keyboard, answering both questions.
📄 basic_input.py: input() always returns a string
name = input("What is your name? ")
print(f"Hello, {name}!")
print(f"Type of name: {type(name)}")
# Even numbers come back as strings
age_str = input("How old are you? ")
print(f"You entered: {age_str}")
print(f"Type: {type(age_str)}")
▶ Output (user types “Rahul” and “28”)
What is your name? Rahul Hello, Rahul! Type of name: <class 'str'> How old are you? 28 You entered: 28 Type: <class 'str'>
What happened here: Both answers came back as strings. Rahul typed 28, but Python stored the text "28", not the number. Try age_str + 1 right now and Python refuses with a TypeError, because you cannot add a number to a piece of text. The fix is to convert it yourself, which is exactly what the next section is about.
Type Casting Input
📄 casting_input.py: convert input to the type you actually need
# Integer input
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")
# Float input
height = float(input("Enter height in meters: "))
print(f"Height in cm: {height * 100:.0f}")
# Boolean-like input (manual conversion)
response = input("Continue? (yes/no): ").strip().lower()
wants_to_continue = response in ("yes", "y", "true", "1")
print(f"Continue: {wants_to_continue}")
▶ Output (user types “28”, “1.75”, “yes”)
Enter your age: 28 Next year you'll be 29 Enter height in meters: 1.75 Height in cm: 175 Continue? (yes/no): yes Continue: True
What happened here: int(input(...)) does two jobs in one line. It reads the string, then turns it into a whole number. Read it inside out, just like nested boxes: input() runs first and hands its text to int(). This works great while the user behaves. But what if someone types “twenty eight” instead of “28”? Then int() cannot make sense of it and the program crashes with a ValueError. That is the whole reason the next section exists.
Handling Bad Input with try/except
📄 safe_input.py: catch conversion errors instead of crashing
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old")
except ValueError:
print("That's not a valid number!")
# A more useful pattern, with a specific error message
user_input = input("Enter a number: ")
try:
number = float(user_input)
print(f"You entered: {number}")
except ValueError:
print(f"'{user_input}' is not a valid number")
▶ Output (user types “abc” then “hello”)
Enter your age: abc That's not a valid number! Enter a number: hello 'hello' is not a valid number
What happened here: try/except ValueError catches the failed conversion and keeps the program alive. Think of it like a seatbelt. You hope you never need it, but the one time the user types something weird, it stops you from going through the windscreen. The full story of exceptions lives in the exception handling tutorial, but this single pattern, wrapping int() or float() in try/except, is one you will reach for straight away.
The Robust Input Loop Pattern
Here is the pattern you will use most in real life: keep asking until the user gives you something valid. It is the same idea as an ATM. Type the wrong PIN and the machine does not crash or hand over cash, it just asks again. This one pattern pulls together everything so far: input(), type casting, validation, and a while True loop.
📄 input_loop.py: the pattern you will copy into every project
def get_age():
"""Keep asking until user enters a valid age."""
while True:
try:
age = int(input("Enter your age (1-120): "))
if 1 <= age <= 120:
return age
print("Age must be between 1 and 120.")
except ValueError:
print("Please enter a whole number.")
def get_rating():
"""Get a rating between 1.0 and 5.0."""
while True:
try:
rating = float(input("Rate this tutorial (1.0-5.0): "))
if 1.0 <= rating <= 5.0:
return rating
print("Rating must be between 1.0 and 5.0.")
except ValueError:
print("Please enter a number like 4.5.")
# Usage
age = get_age()
rating = get_rating()
print(f"\nAge: {age}, Rating: {rating}")
▶ Output (user types “abc”, “-5”, “28”, then “6”, “4.5”)
Enter your age (1-120): abc Please enter a whole number. Enter your age (1-120): -5 Age must be between 1 and 120. Enter your age (1-120): 28 Rate this tutorial (1.0-5.0): 6 Rating must be between 1.0 and 5.0. Rate this tutorial (1.0-5.0): 4.5 Age: 28, Rating: 4.5
What happened here: The while True loop just keeps spinning until a return hands back a valid value and ends the function. Two guards sit inside it. Typed letters instead of a number? except ValueError catches that. Typed a real number but out of range, like 6 out of 5? The if check sends them back. Between those two, nothing the user types can break the program. It either gets good input or politely asks one more time.
Multiple Inputs on One Line
Sometimes one prompt has to collect several values at once. Say a user named Niranjan fills in his name and age on a single line. .split() works like a chapati cutter rolling across dough: one line goes in, neat separate pieces come out, cut wherever the separator appears.
📄 multi_input.py: split one line into several values
# Space-separated values
data = input("Enter name and age (space-separated): ").split()
name, age = data[0], int(data[1])
print(f"{name} is {age} years old")
# Comma-separated values
scores = input("Enter 3 scores (comma-separated): ").split(",")
scores = [int(s.strip()) for s in scores]
print(f"Scores: {scores}, Average: {sum(scores)/len(scores):.1f}")
▶ Output (user types “Niranjan 32” and “88, 92, 76”)
Enter name and age (space-separated): Niranjan 32 Niranjan is 32 years old Enter 3 scores (comma-separated): 88, 92, 76 Scores: [88, 92, 76], Average: 85.3
What happened here: .split() chops one line into a list of pieces. With no argument it splits on spaces, so “Niranjan 32” becomes ["Niranjan", "32"]. Pass it a comma and it splits on commas instead. After that, each piece is still text, so we cast the ones we need: int(data[1]) for the age, and a small list comprehension to turn every score into an int. The .strip() on each score quietly removes the stray space after each comma, which is why “88, 92, 76” works and does not choke on the spaces.
One honest note: the square-bracket pieces here, data[0] and that compact [int(s.strip()) for s in scores] line, are a sneak peek. You will meet this list syntax properly in the lists and list comprehension tutorials, so do not stress if those lines look strange right now.
When You Will Use This
- CLI (Command-Line Interface) tools: Any command-line application that asks the user for configuration, file paths, or confirmation prompts
- Interactive scripts: The number guessing game in the number guessing game tutorial, calculators, quiz programs
- Data entry: Small scripts that collect information and write it to a file or database
Common Mistakes
Mistake 1: Doing math on raw input
🚫 Wrong
age = input("Age: ")
print(age + 1) # TypeError: can only concatenate str (not "int") to str
✅ Correct
age = int(input("Age: "))
print(age + 1) # works, age is now an int
Why: The raw value from input() is text. Python reads age + 1 as “glue these together”, but it cannot glue a number onto a string, so it stops with a TypeError. Wrap the input in int() first and age + 1 becomes real addition.
Mistake 2: No validation on the cast
🚫 Crashes on bad input
score = int(input("Score: ")) # user types "abc", ValueError crash
✅ Robust
try:
score = int(input("Score: "))
except ValueError:
print("Invalid number")
Why: int("abc") has no way to become a number, so it raises ValueError: invalid literal for int() with base 10: 'abc' and the bare version takes your whole program down with it. The try/except version catches that one error and lets you respond calmly instead of crashing.
Best Practices
- DO always
.strip()user input to remove accidental whitespace - DO wrap type conversions in
try/except ValueError - DO include the expected format in the prompt:
"Enter date (YYYY-MM-DD): " - DO use the
while True+returnpattern for robust input collection - DON’T assume
input()returns anything other than a string - DON’T use
eval(input()), because it runs whatever the user types as live code and is a massive security hole
Conclusion
Three things to carry away. The Python input() function always returns a string, so always cast it, and always validate it. The combo of while True, try/except, and a range check is the grown-up way to collect Python input from users, and you will reuse it in pretty much every interactive program you ever write. Get this pattern into your fingers now and the rest of the series gets a lot easier.
Next up: Conditional Statements, making decisions with if, elif, and else. And if you want the full roadmap from fundamentals to AI/ML projects, browse the Python + AI/ML tutorial series home.
Practice Exercises
- Exercise 1: Ask for name and birth year, calculate and display age.
- Exercise 2: Create a 3-question quiz tracking score with percentage.
- Exercise 3: Build an interactive unit converter running until user types quit.
Frequently Asked Questions
What does Python input() return?
input() always returns a string (str), regardless of what the user types. If the user types 42, you get the string '42', not the integer 42. You must explicitly convert with int(), float(), etc.
How do I get integer input in Python?
Use int(input('prompt: ')) to convert the string to an integer. Wrap it in try/except ValueError to handle cases where the user types non-numeric text.
Why should I not use eval(input())?
eval() executes any Python expression. If a user types __import__('os').system('rm -rf /'), it runs that command. Never use eval() on user input. Use explicit type conversion functions like int() or float() instead.
How do I take multiple inputs on one line in Python?
Use input().split() for space-separated values or input().split(',') for comma-separated values. Then unpack or index into the resulting list. Example: name, age = input('Name and age: ').split().
How do I validate user input in Python?
Combine a while True loop with try/except for type validation and an if statement for range/format validation. Return the value when it passes all checks. This pattern keeps asking until valid input is received.
Interview Questions on Python input()
Interviewers rarely ask for definitions. They ask what happens in situations like these.
Q: How is input() in Python 3 different from Python 2?
Python 2 had two functions: raw_input(), which returned the typed text as a string, and input(), which dangerously evaluated the text as Python code. Python 3 dropped the unsafe one and renamed raw_input() to input(). So in Python 3, input() always returns a plain string and never executes anything. If you need the old eval behavior, you almost certainly do not, for the security reasons covered in the FAQ.
Q: Can input() itself raise an exception, even before any type casting?
Yes, two common ones. If the input stream ends, for example the user presses Ctrl+D on Linux/macOS or Ctrl+Z then Enter on Windows, input() raises EOFError. If the user presses Ctrl+C while the program is waiting, Python raises KeyboardInterrupt. A ValueError, on the other hand, never comes from input(); it comes from the int() or float() you wrapped around it.
Q: Your script runs fine when you launch it by hand, but a scheduled overnight job runs it and it crashes with EOFError. What happened?
Scheduled jobs run without a keyboard attached, so there is no interactive stdin for input() to read from. The stream is empty, input() hits end-of-file immediately, and raises EOFError. The fix is to stop prompting in automated contexts: read values from command-line arguments, a config file, or environment variables instead, or pipe the expected answers into the script.
Q: A user named Anvi types “42.0” when your program asks for her age, and int(input()) crashes with ValueError even though it looks like a number. Why, and what is the fix?
int() only accepts strings that spell a whole number, so int("42.0") fails because of the decimal point. If you want to accept both forms, convert in two steps, int(float(text)), or catch the ValueError and re-prompt using the loop pattern from this post. Whichever you pick, keep the try/except, because the next user will type something even stranger.
Q: Does int(input()) cope with extra spaces, like a user typing ” 28 “?
Yes. int() and float() both ignore leading and trailing whitespace, so int(" 28 ") returns 28 without help. But when you keep the input as a string, for names or yes/no answers, the spaces stay, and "yes " is not equal to "yes". That is why the habit of calling .strip() on string input is worth building early.
Q: How would you ask the user for a password without it showing on screen?
input() echoes every character as it is typed, which is wrong for secrets. Use the standard library instead: from getpass import getpass, then password = getpass("Password: "). It prompts the same way but suppresses the echo, and it still returns a plain string you can validate like any other input.
Want more? the official Python documentation documents everything this post could not fit.
Related Posts
Previous: Python: String Formatting (%, format(), f-strings Compared)
Next: Python: Conditional Statements (if, elif, else) with Examples
Series Home: Python + AI/ML Tutorial Series

No comment