Pylerno
English

Validation

Check both parseability and the meaning of external data.

On this page

The concept

Conversion answers whether text can represent a value of a type. Validation answers whether that value is allowed here. A score of 120 is numeric but outside this program's domain. float also accepts special values such as nan and inf, so a numeric type alone is insufficient.

Use if and raise to enforce input rules. ValueError communicates that a value is inappropriate for the operation. Keep that rule in a reusable function; translate its failure into a user-facing message at the boundary. Assertions are not suitable for user validation because optimized execution can remove them.

Worked example

python
import math


def parse_score(text):
    score = float(text)
    if not math.isfinite(score) or not 0 <= score <= 100:
        raise ValueError("Score must be finite and between 0 and 100.")
    return score


for raw in ["85", "120", "abc", "nan"]:
    try:
        print("Score:", parse_score(raw))
    except ValueError as error:
        print("Invalid data:", error)

Trace the result

  1. parse_score first converts the text to float.
  2. math.isfinite rejects nan and infinity, and the range comparison enforces 0 through 100.
  3. The caller catches invalid cases and displays the reason without changing the validation rule.
text
Score: 85.0
Invalid data: Score must be finite and between 0 and 100.
Invalid data: could not convert string to float: 'abc'
Invalid data: Score must be finite and between 0 and 100.
Line-by-line walkthrough

Line 1: import math

Load math (mathematical operations and finite-number checks). Importing makes these names available; it is not a call to every function in the module.

Lines 4–8: def parse_score(text):

Define the function parse_score with input names text. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.

Line 5: score = float(text)

Evaluate float(text), then bind or update score with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Lines 6–7: if not math.isfinite(score) or not 0 <= score <= 100:

Evaluate not math.isfinite(score) or not 0 <= score <= 100. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.

Line 7: raise ValueError("Score must be finite and between 0 and 100.")

Raise ValueError('Score must be finite and between 0 and 100.'). Normal execution stops here unless an enclosing handler catches it. A from cause, when present, preserves the reason for a translated error.

Line 8: return score

Evaluate score and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.

Lines 11–15: for raw in ["85", "120", "abc", "nan"]:

Obtain each item from ['85', '120', 'abc', 'nan'] and bind it to raw before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Lines 12–15: try:

Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.

Line 13: print("Score:", parse_score(raw))

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Handler for ValueError: control reaches this suite only for a matching exception from the protected body.

Line 15: print("Invalid data:", error)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

Do not replace invalid values with zero unless zero is genuinely the specified result. That can silently corrupt totals or averages.

Check your understanding

What does this program print?

python
score = 101
print(0 <= score <= 100)
Choose one answer

Search documentation

Share this page