Python if, elif and else: Making Decisions
An if statement runs a block of code only when a condition is true. Add elif ("else if") branches to test more conditions in order, and an optional else to catch everything that did not match.
How Python picks a branch
Python checks the conditions from top to bottom and runs the first branch whose condition is true, then skips the rest of the chain. The order of branches therefore matters. In a grading scale, test the highest threshold first: if score >= 70 came before score >= 90, a score of 95 would stop at the first match and get a C.
Every branch line ends with a colon, and its body is indented. You can have any number of elif branches, and at most one else, which must come last.
Expected output
Grade: B Status: pass Name is empty
One-line conditional expressions
When you only need to choose between two values, a conditional expression is shorter than a full statement: value_if_true if condition else value_if_false. In the example, status becomes "pass" because 83 is at least 60. Keep these for simple choices; nested conditional expressions become hard to read fast.
Testing for empty values
Because empty strings and lists are falsy, if not name: reads naturally as "if name is empty". This is clearer than comparing with "" and also works for None.
What about match?
Python 3.10 added the match statement for structural pattern matching, which compares a value against several shapes or literals, similar to switch in other languages. Our examples are tested on Python 3.9, so we do not include a runnable match example here. For plain value checks, an if/elif chain or a dictionary lookup does the same job on every Python 3 version.
Common mistakes
- Putting the broadest condition first, so later branches never run.
- Writing
else ifinstead ofelif. - Forgetting that
elsehas no condition.else score < 50:is a syntax error. - Deep nesting. If you are three levels deep, consider combining conditions with
andor returning early from a function.
Summary
if/elif/elseruns the first branch whose condition is true.- Order branches from most specific to most general.
a if cond else bchooses between two values in one line.matchexists from Python 3.10;if/elifworks everywhere.
Quiz: if, elif, else