Knowledgebase

Conditions and Making Decisions Print

  • python, guide, howto, solution, zillionkinghost, hosting, support
  • 0

Branching.

WHAT A CONDITION DOES

Runs code only when something is true.

THE STRUCTURE

If, optionally followed by alternatives, optionally followed by a fallback.

WHAT COUNTS AS TRUE

Non-zero numbers, non-empty text and non-empty collections are treated as true.

Zero, empty values and the absence of a value are treated as false.

WHY THAT MATTERS

It allows concise checks, and it causes confusion when a value could legitimately be zero.

THAT CASE

Check explicitly for the absence of a value rather than relying on truthiness, where zero is valid.

COMPARISONS

Equality, inequality, and ordering.

Note that equality and identity are different checks.

COMBINING CONDITIONS

With and, or, and not.

Keep them readable. A condition needing careful reading should be split.

WHAT TO AVOID

Deeply nested conditions Repeating the same check in several places Conditions with side effects

WHAT TO PREFER

Returning early rather than nesting deeply.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot