Python input(): How to Read and Validate User Input

input() always returns a string. Always — even when the user types a number.

That single fact causes most of the bugs people hit with it: comparisons that fail, arithmetic that throws TypeError, and validation that passes when it shouldn’t.

This guide covers how input() actually works, how to convert what it returns, and how to validate without crashing when someone types something unexpected — which they will.

The short version
What it returnsAlways a str, never a number
Convertingint() or float() — both can raise ValueError
Validating safelytry/except ValueError, not .isdigit()
Empty input returnsAn empty string — not None
Never do thisPass user input to eval()

How input() works

It prints a prompt, waits for the user to press Enter, and returns what was typed — as a string.

name = input("What's your name? ")print(name) # Ana print(type(name)) # <class 'str'>

Three details worth knowing:

The prompt is optional. input() with no argument waits silently — which is confusing for the user, so always pass one.

The newline is stripped. The Enter keystroke isn’t included in what you get back.

And nothing else is stripped. Leading and trailing spaces come through exactly as typed.

⚠️ If the user just presses Enter, you get an empty string — "", not None. That distinction matters when you test for it.

The one fact that causes most bugs

The input function in Python always returns a string, so arithmetic on it raises TypeError until it is converted with int

Even when the user types a number, you get a string.

age = input("Your age: ") # user types 42print(age) # 42 print(type(age)) # <class 'str'>age + 1 # TypeError: can only concatenate str (not "int") to strage % 2 # TypeError: not all arguments converted during string formatting

The value looks like a number and behaves like text. Arithmetic fails, comparisons give wrong answers, and the error message rarely points at the real cause.

The fix is to convert explicitly:

age = int(input("Your age: "))print(age + 1) # 43 print(age % 2) # 0

Converting: int() and float()

Both work, and both can fail.

int("42") # 42 float("3.5") # 3.5int("abc") # ValueError: invalid literal for int() with base 10: 'abc'int("3.5") # ValueError: invalid literal for int() with base 10: '3.5'

⚠️ The second failure surprises people: int("3.5") does not round or truncate — it raises. int() parses integers, and “3.5” isn’t one.

If you want to accept decimals and end up with a whole number, convert twice: int(float("3.5")) gives 3.

Validating: the wrong way and the right way

Why .isdigit() is not enough

It’s the most recommended method online, and it’s wrong in three ways.

"42".isdigit() # True ← fine "-5".isdigit() # False ← but int("-5") works "3.5".isdigit() # False ← and float("3.5") works "٣".isdigit() # True ← Arabic-Indic digit "²".isdigit() # True ← superscript two

It rejects valid negative numbers and decimals, and accepts characters that int() may not handle as you expect.

Comparison showing isdigit rejects valid negative numbers and decimals while accepting Arabic-Indic digits and superscripts, with try and except ValueError as the correct approach

The right way: ask forgiveness, not permission

while True: try: age = int(input("Your age: ")) break except ValueError: print("Please type a whole number.")print(f"You are {age}")

int() already knows what it can parse — let it decide, and catch the failure. This is the standard Python approach, and it’s why the language has a name for it: easier to ask forgiveness than permission.

⚠️ The loop matters. Without it, the program tells the user they were wrong and then continues with no value.

A reusable pattern

Once you write this twice, extract it:

def ask_int(prompt, minimum=None, maximum=None): while True: raw = input(prompt).strip() try: value = int(raw) except ValueError: print("That's not a whole number.") continue if minimum is not None and value < minimum: print(f"Must be at least {minimum}.") continue if maximum is not None and value > maximum: print(f"Must be at most {maximum}.") continue return valueage = ask_int("Your age: ", minimum=0, maximum=130)

Note the =None defaults — the same pattern covered in our guide on None in Python, and the reason it’s safe here.

And the .strip() handles the user who typed a space before the number.

Handling empty input

Pressing Enter without typing returns an empty string:

answer = input("Your name (Enter to skip): ")if answer == "": print("Skipped") else: print(f"Hello, {answer}")

⚠️ Beware of if not answer. It’s true for an empty string — but it would also be true for "0" if you’d converted first. When the meaning is “nothing was typed”, compare to "" explicitly.

Since Python 3.8, the walrus operator makes the retry loop shorter:

while not (name := input("Your name: ").strip()): print("Name can't be empty.")print(f"Hello, {name}")

Validating with regular expressions

For format rules that aren’t about type — an email shape, a postcode, an ID pattern — a regex is the right tool.

import reusername = input("Username (letters and numbers only): ")if re.match(r"^[a-zA-Z0-9]+$", username): print("Valid") else: print("Invalid — letters and numbers only")

⚠️ Don’t forget import re — it’s the most common omission when copying regex examples.

And a warning about email: a regex that truly validates an email address per the specification is famously enormous and still imperfect. For real applications, use a library — or simply send a confirmation message, which is the only test that actually proves the address works.

Validating JSON input

If you expect a JSON string, parse it inside a try — don’t test truthiness.

import jsonraw = input("Paste JSON: ")try: data = json.loads(raw) print("Valid JSON:", data) except json.JSONDecodeError as e: print("Invalid JSON:", e)

⚠️ Why truthiness fails here: these are all valid JSON and all falsy.

json.loads("{}") # {} → falsy, but valid json.loads("[]") # [] → falsy, but valid json.loads("null") # None → falsy, but valid json.loads("0") # 0 → falsy, but valid json.loads("false") # False → falsy, but valid

Writing if json.loads(raw): reports five valid inputs as invalid. The exception is the only reliable test.

⚠️ Never pass input to eval()

This is the security section, and it’s short because the rule is absolute.

value = eval(input("Enter a number: ")) # NEVER DO THIS

eval() executes whatever is typed as Python code. A user who types __import__('os').system('rm -rf ~') gets exactly that behaviour.

The same applies to exec(). If you need a number, use int() or float() — they parse, they don’t execute.

⚠️ And if you’re reading input in a program that runs on a server, this stops being a theoretical concern.

Reading multiple values at once

input() reads one line. To get several values from it, split:

# user types: 3 7 12 numbers = input("Numbers separated by spaces: ").split() print(numbers) # ['3', '7', '12'] ← still stringsvalues = [int(n) for n in numbers] print(values) # [3, 7, 12] print(sum(values)) # 22

And to unpack into named variables:

# user types: Ana 30 name, age = input("Name and age: ").split() age = int(age)

⚠️ This raises ValueError if the user types the wrong number of items — so it belongs inside a try in real code.

When input() isn’t the right tool

input() reads from standard input, which means it assumes someone is sitting there. In three situations, it’s the wrong choice:

Passwords. input() echoes what’s typed to the screen. Use getpass.getpass(), which doesn’t.

Scripts run automatically — cron jobs, CI pipelines, containers. There’s no one to answer, and input() raises EOFError when standard input is empty. Use command-line arguments with argparse, or environment variables.

Web applications. There’s no terminal at all. Input comes from HTTP requests, handled by the framework.

⚠️ The EOFError is worth knowing — it’s what you get when a script expecting input runs somewhere there isn’t any, and the message doesn’t obviously say that.

Where your script runs without a terminal

A script that waits for input() in a cron job raises EOFError and dies silently. Copahost VPS plans give you root access, your choice of Python version, real cron, and logs you can actually read when something fails at 3am. From €3.99/month, with snapshots.

See VPS plans

Frequently asked questions

Does input() always return a string?

Yes, always — even when the user types digits. This is the source of most bugs with it. If you need a number, convert explicitly with int() or float(), and be ready for the conversion to fail.

Why does input() + a number raise TypeError?

Because you’re adding text to a number. input() returned "42", not 42, and Python won’t guess what you meant. Wrap it: int(input(...)).

How do I check if the input is a number?

Try converting it inside a try/except ValueError. Don’t use .isdigit() — it rejects "-5" and "3.5", which are valid numbers, and accepts characters like "٣" and "²" that aren’t what you expect. int() already knows what it can parse.

What happens if the user just presses Enter?

You get an empty string — "", not None. Test with if answer == "" when you mean “nothing was typed”, since if not answer would also catch other falsy values if you’d converted first.

Why does int("3.5") fail?

Because int() parses integers, and "3.5" isn’t one — it doesn’t round or truncate. If you want to accept decimals and end up with a whole number, convert twice: int(float("3.5")) gives 3.

How do I read several values from one line?

Use .split(), which returns a list of strings, then convert each one: [int(n) for n in input().split()]. You can also unpack directly — name, age = input().split() — but that raises ValueError if the count doesn’t match, so it belongs in a try.

How do I make the program ask again until the input is valid?

Put the conversion in a while True loop with try/except, and break only when it succeeds. Without the loop, the program tells the user they were wrong and then continues with no value.

Is eval(input()) safe?

No, and it never is. eval() executes whatever is typed as Python code — a user can read files, delete data or run commands. If you need a number, use int() or float(), which parse rather than execute. The same applies to exec().

How do I read a password without showing it on screen?

With getpass.getpass() from the standard library. It works like input() but doesn’t echo what’s typed. input() always displays the characters, which makes it wrong for anything sensitive.

Why does my script raise EOFError on the server?

Because input() reads from standard input, and in a cron job, container or CI pipeline there’s nobody to type. Use argparse for command-line arguments, or environment variables, instead of waiting for input that will never come.

How do I validate an email address from input?

Not with a regex, realistically. A pattern that truly matches the email specification is enormous and still imperfect. Use a dedicated library for a basic shape check, and then send a confirmation message — which is the only test that proves the address actually works.

Can I set a default value for input?

Not directly, but the pattern is simple: check for the empty string and substitute. answer = input("Name [Ana]: ").strip() or "Ana" gives "Ana" when the user just presses Enter. ⚠️ Use this only with strings — with numbers, or would also replace a legitimate zero.

Conclusion

input() is one of the first functions anyone learns in Python, and one of the last they stop getting wrong. The reason is a single fact: it always returns a string, even when the user typed a number.

Three things follow from that. Convert explicitly with int() or float(), and expect them to fail. Validate with try/except ValueError, not .isdigit() — the conversion already knows what it can parse, and .isdigit() rejects negatives and decimals while accepting characters you didn’t intend. And wrap it in a loop, so a wrong answer means “ask again” rather than “continue with nothing”.

And one rule with no exceptions: never pass user input to eval(). It executes whatever was typed as Python code. If you need a number, int() parses it — which is all you wanted in the first place.

Share the Post:
Picture of Gustavo Gallas

Gustavo Gallas

Graduated in Computing at PUC-Rio, Brazil. Specialized in IT, networking, systems administration and human and organizational development​. Also have brewing skills.