Checking for invalid input in Python means deciding, before you use a value, whether it meets every requirement your code depends on, then reacting in a defined way when it doesn't. The dependable pattern is to validate at three points: parse the raw input into a proper type, apply constraints to that type, and enforce rules that depend on context or other data. Each layer raises a specific exception or returns a clear error rather than letting bad data travel deeper. The condition that ties it all together is that validation must happen at the boundary where data enters, not scattered through the code that consumes it.

That sounds tidy, and in practice it is, but most broken input handling comes from skipping a layer or muddling two. Parsing "12" into 12 is not the same as confirming 12 is within range, and neither is the same as confirming a username in field A is unique given what's already in field B. Keep those three jobs separate and the code stays readable and testable. The sections below walk through the workflow, the tools Python gives you for each layer, the failure modes that trip people up, and how to test the whole thing.

1: Map the boundary first, then the rules

Before you write a single if, write down where untrusted data enters your program. The usual boundaries are command-line arguments, input() calls, file reads, environment variables, HTTP request bodies and query strings, values from a database or message queue, and the return values of third-party libraries. Data that crosses one of those lines is untrusted by default, even if it "usually" looks right.

Next, state the rules for each field as a short contract. "Age must be an integer from 0 to 130." "Quantity must be a positive integer no larger than stock on hand." "Email must parse as an address and be unique in the accounts table." Notice how the first rule is fully local, the second depends on inventory, and the third depends on external state. Writing the rules this way tells you which layer each belongs to and which checks you can unit-test in isolation.

A useful discipline is to give each boundary function a single responsibility: it accepts raw input, validates it, and either returns clean, typed data or raises. Everything downstream can then assume it received valid data and needs no defensive clutter. That assumption is what makes the boundary worth building. If half your functions re-check the same field, the boundary was never real.

2: Layer one: parse raw input into the type you actually want

The first job is conversion. Raw data arrives as text or bytes, and conversion failures are a category of invalid input in their own right. Python's built-in constructors already enforce form: int("12") succeeds and int("twelve") raises ValueError; float("1.5") succeeds and float("1.5kg") raises. Let those exceptions do the first cut, but catch them at the boundary and turn them into a message a human or caller can act on.

Three details matter here. Catch the specific exceptions you expect, not bare except:; a bare handler also swallows KeyboardInterrupt and programming mistakes. Re-raise a new error with context rather than returning None, so a caller can't accidentally treat a failed parse as a valid falsy value. And keep the !r formatting so an empty string or hidden whitespace is visible in the message.

One genuine limitation: int() accepts surrounding whitespace and underscores in some textual contexts (like "1_000"), and it accepts a leading + or -. If your rules forbid those, strip and check first. Also decide on locale- and format-sensitive numbers early. "1,000" fails int(), and float("1,5") fails too even though it's a valid decimal in many locales. Parsing those formats is a deliberate step, not something you get for free, and treating a localized format as invalid when the user considers it valid is a real source of bad error messages.

For structured formats, parse rather than pattern-match. json.loads, datetime.date.fromisoformat, and decimal.Decimal all validate structure as they convert and raise on malformed input. Decimal is worth preferring over float when money or exact decimal quantities are involved, because binary floating point can't represent most decimal fractions exactly, so a validation range like "no more than 19.99" can behave surprisingly with floats. Explicitly reject non-finite values if your domain requires real numbers: float("nan") and float("inf") parse successfully but often break comparisons and arithmetic downstream.

3: Layer two: enforce constraints on the parsed value

Once you hold a real type, apply the local rules: ranges, allowed sets, lengths, patterns, and sign. These checks are cheap, pure, and easy to test. Prefer the clearest construct for the job rather than a chain of nested ifs.

Membership in a fixed set is a good fit for in with a set literal. For numeric ranges, plain comparisons read well. If you don't need to know which rule failed, assert-style guard clauses that raise early keep indentation flat. If you do need per-rule messages, collect them and raise one error listing every problem, which is friendlier than making the user fix issues one at a time.

That bool check deserves a note. In Python, True and False are instances of int, so isinstance(True, int) is True and True == 1. If you validate an integer field by type alone, a boolean can slip through and be treated as 1 or 0. The explicit isinstance(value, bool) guard closes that gap, and it's cheap insurance on APIs and config parsers where booleans are common.

For strings, decide precisely what "valid" means. A length check with len() after str.strip() catches whitespace-only input that a naive truthiness test misses: bool(" ") is True even though a user who typed a space intended nothing. If you restrict characters, str.isalnum() and friends cover common cases; for richer patterns, a compiled re pattern with re.fullmatch is clearer than re.match because it anchors both ends and rejects trailing junk. Keep pattern rules narrow enough to explain in an error message. A regex nobody can read is a maintenance liability, not a validator.

4: Layer three: context and cross-field rules

The checks that need other data belong last, after cheap syntax checks pass. This ordering matters for speed and for error quality: there's little point querying a database for a username when the submitted username is empty or 400 characters long. Do the local checks first, then the expensive or stateful ones.

Context checks include uniqueness against stored records, referential checks that a foreign key exists, aggregate limits like a daily transfer cap, consistency between fields (a start date before an end date, a shipping address matching a billing country where required), and authorization, meaning whether this caller may submit this value at all. These are often the rules most worth getting right, because they carry business meaning, and they're usually the ones that change over time.

There's a subtlety in this layer: validation and action aren't atomic. Checking that a username is free and then inserting it in a separate step leaves a race window where two requests can both pass the check. The fix is to let the storage layer enforce the rule with a unique constraint and handle the integrity error, using validation for a useful message and the database for the guarantee. Similarly, balance and limit checks should be re-verified at the moment of the update, typically inside a transaction with appropriate locking, not just at input-parsing time. Treat the layer-three check as a courtesy, not a proof of safety.

5: Choosing the mechanism: exceptions, return values, or validators

Python gives you three broad styles, and mixing them carelessly is a common source of inconsistency.

Exceptions are the idiomatic default for invalid input that the caller didn't anticipate or can't reasonably ignore. They can't be silently dropped, they carry tracebacks, and they separate the happy path from the failure path. Use custom exception classes for domain errors so callers can catch precisely what they mean to handle.

Return values, such as None or a tuple of (ok, value, error), suit situations where invalidity is an expected, routine outcome the caller will branch on anyway—say, validating one field in a large form where you want to collect all errors and keep going. The danger is callers who forget to check, so pair this style with clear names and, where possible, types that make the failure state hard to mistake for success.

Validator objects or schema libraries fit when you have many fields with declarative rules: they centralize the rules, produce consistent multi-error reports, and reduce boilerplate. For JSON input, jsonschema can validate structure and types against a schema document. For command-line parsing, argparse handles types, choices, and required arguments and raises its own usage errors. These tools share one caveat: they validate the shape they're told about, and they are not a substitute for your domain rules in layers two and three. A schema can say a quantity is an integer; it can't know your inventory.

Whichever you choose, be consistent within a boundary. A function that sometimes raises, sometimes returns None, and sometimes returns an error string is a trap for whoever calls it next.

6: Common failure cases and how to avoid them

Several input bugs recur often enough to deserve their own list.

Catching too broadly or not at all. A bare except: hides bugs like misspelled variable names. A bare try: around a large block can catch errors from unrelated lines, making real defects look like bad user input. Keep try blocks as small as possible and name the exception types you expect.

Validating the wrong copy of the data. If you validate a normalized version (stripped, lowercased) but then use the original, your checks and your actions diverge. Normalize once, use the normalized value everywhere, and be explicit about whether case or whitespace matter for a given field.

Trusting interpolation into queries or commands. Validating that a field isn't empty is not injection protection. Use parameterized queries for SQL and avoid shell=True for subprocess calls; validation does not replace correct construction of the operation itself.

Assuming browser or upstream checks are enough. Client-side validation improves UX but is trivially bypassed. Any value that arrives at your code needs checking on the server or in the library regardless of what the interface permitted.

Confusing "valid" with "safe." Input might be perfectly formed yet still harmful to your assumptions, like an enormous string that exhausts memory or a deeply nested JSON payload. Payload-size limits are validation too, just at a different granularity, and they belong at the boundary alongside everything else.

Using assertions for user input. assert statements are intended for internal invariants and are stripped when Python runs with optimizations enabled, so a validation that only lives in an assert can silently disappear in production. Raise real exceptions for input checks.

Type confusion in dynamically typed code. Values from JSON or config can be lists or dicts where you expect scalars. Check types explicitly before operating on them, especially before indexing, iterating, or doing arithmetic, and remember the boolean-is-an-int wrinkle from earlier.

7: Building good error messages and deciding what to do with failures

Validation only helps if the response is useful. A good message says what was wrong, which field, what input caused it, and what would be acceptable. "Invalid input" satisfies none of those. "quantity must be a positive integer, got '0'" does, and it gives the person debugging something concrete without leaking internals.

There's a security boundary here too. Error text returned to untrusted callers shouldn't reveal stack traces, query fragments, or system paths; log the detail separately and return a safe summary. Validation errors that echo the offending input should be careful with terminal escape sequences and markup, since echoing raw input into a log or page can itself cause trouble.

Decide the recovery policy per boundary. A command-line tool might print the error and exit with a nonzero status. A web API might return a structured 400-level response listing field errors. A batch importer might skip bad rows, record them, and continue. Whatever the policy, make it uniform and document it, because inconsistent failure behavior is almost as bad as no validation. For iteratively improving forms, a common pattern is a two-phase approach: validate everything, gather all problems, then present them together.

8: Testing invalid input deliberately

The only way to know your checks work is to feed them bad data on purpose. Build a small table of cases per boundary: valid values, boundary values at the edges of each range, and clearly invalid values in many shapes—empty strings, whitespace, wrong types, None, True, nan, very large numbers, strings with leading zeros, values in a different locale's format, and unexpected structures.

The cases worth the most effort are the ones that differ by a single character or a single unit at the edge of a rule: 19.99 versus 20.00, an empty list versus a list with one empty string, "0" versus 0 versus False. These catch off-by-one and type-confusion bugs that nominal "happy path" tests never reach.

Success looks like this: every boundary function has tests for valid, edge, and malformed input; your error messages name the field and the reason; and downstream code has no redundant re-validation but still behaves sanely if the boundary is bypassed during development. A practical check is to run your importer or endpoint with deliberately corrupted fixtures and confirm that bad data is rejected at the edge and that observed behavior matches the documented recovery policy. If a malformed record slips through to cause a confusing error deep in the stack, the boundary is leaking.

As a stop condition, treat any input path that accepts file formats, parses executable content, or handles credentials and payments as worth a professional review, and any security exception during validation as something to investigate rather than silence. When a validation failure reveals that data already in storage is malformed, stop writing new checks around it and plan a cleanup, because defending the boundary is only half of data hygiene.

9: Scaling the workflow as the rules grow

A handful of fields with simple rules fits comfortably in explicit functions, and that's usually the right starting point. As fields multiply, move the rules into one place per boundary—a validation module or a declarative schema—so the contract lives in a single spot and tests target that module directly. Separate parsing (string to type) from validation (type to validity) from business rules (validity to permission), and keep that same three-step shape in every boundary you build. The pattern scales because each layer can be tested and changed independently, and because new rules slot in where they belong instead of being bolted onto wherever input happens to arrive.