Skip to content
Forge Learn/Control Flow

Conditionals: if / elif / else

5 min read

You'll learn to

  • -Write if / elif / else chains to branch program logic
  • -Combine conditions with and, or, and not
  • -Nest conditionals when a decision depends on more than one level of logic
  • -Know that Python has no switch statement, and what replaces it

So far every snippet in this course has run top to bottom, every line, every time. Real programs need to make decisions - do this if a condition holds, do something else if it doesn't. That's what conditionals are for.

Comparison Operators

  • -== equal to (note: two equals signs - one = is assignment, a very common typo bug)
  • -!= not equal to
  • -< / > less than / greater than
  • -<= / >= less than or equal to / greater than or equal to

if / elif / else

Try it yourself

Python evaluates conditions top to bottom and runs the first branch that matches, then skips the rest entirely - even if a later condition would also be true. elif (short for "else if") lets you chain as many conditions as you need; else is optional and catches anything not matched above. Note that Python uses indentation, not braces, to mark what belongs inside each branch - four spaces is the near-universal convention, and getting the indentation wrong is a real syntax error, not just a style nitpick.

Combining Conditions: and, or, not

Try it yourself

and requires both sides to be true, or requires at least one, and not flips a condition's truth value. Unlike some languages, Python spells these out as words rather than symbols like && or || - one of many small ways Python favors reading like plain English.

Nesting Conditionals

Try it yourself

Nesting is what you reach for when a decision genuinely depends on the outcome of a previous decision. It's powerful, but it's also the fastest way to make code hard to read - three or four levels deep and a reader has to hold a lot of context in their head at once. Often, combining conditions with and (like age >= 18 and has_ticket) reads more clearly than nesting two separate if statements, when the logic allows it.

No switch Statement (and match/case, Briefly)

Unlike languages with a dedicated switch statement, Python has traditionally handled "check this value against several options" purely with if / elif / else chains - and that's exactly what you should reach for as a beginner. Modern Python (3.10+) does add a match/case statement for this exact pattern, worth knowing exists even though this course won't lean on it:

Try it yourself

match/case is genuinely useful once your conditions get complex (especially matching on the shape of data), but if / elif / else handles everything you'll need for the rest of this course - don't feel behind for sticking with it.

ScaleDojo Logo
Initializing ScaleDojo