EMZETT.
Login

if…else

In short: The basic control structure for branching: if a condition is true, one code block runs, otherwise (else) another one does.

In more detail: The else branch is optional — a plain if statement with no else only runs its block if the condition is met and otherwise simply continues with the rest of the code. Several conditions can be chained via else…if chains; for many possible fixed values, a switch statement is often more readable.

In Depth

if age >= 18:
    print("Adult")
else:
    print("Minor")

if...else is one of the first control structures learned in any language, because it represents the most fundamental building block of any non-trivial program logic: a decision based on a condition. Together with loops (repetition), branches form the two basic control structures that practically any program flow is built from — any program logic, no matter how complex, can ultimately be traced back to these two building blocks (plus simple sequence, i.e. “one instruction after another”).

A frequently overlooked pitfall is indentation/block membership: in languages with curly braces, without explicit braces only the IMMEDIATELY next statement belongs to the if block:

if (condition)
    doSomething();
    doSomethingElse();  // DOES NOT BELONG TO THE IF! Always runs, regardless of the condition

This mistake is especially tricky because the indentation in the editor suggests both lines belong to the if, while the compiler sees it differently. This is why it’s considered best practice to always use explicit braces, even for a single statement — Python avoids this problem structurally, since indentation there is itself part of the syntax and not just a visual convention.

Another important point is the short-circuit character of condition evaluation: for compound conditions with AND/OR, evaluation stops as soon as the result is determined (see Logical Operators) — this is deliberately used to run risky checks (e.g. reading a value that might not even exist) only AFTER a protective pre-check.

See also: if Statement, else…if, Switch Statement