Python branching (if + else + elif)

making decisions between or among conditions
2025-11-04 12:04
// updated 2025-11-06 20:56

Naturally, once we have learned how to use operators, we might wish to use them to control the flow of the program with "what-if" (or rather "if-else") scenarios; in Python we have the following statements to help us branch:

  • if (the first branch)
  • else (the other branch)
  • elif (any other branch after the if and before the else statement)

Things to note:

  • an if statement can live without an else and elif statements
  • an else statement must have an if but can live without an elif
  • an elif statement must have both if and else

Each of the three statements ends with a colon (:) and contains an indented code block!

if statements

An if statement will typically have as a condition, a comparison operator (or a question about an existence of some variable):

temperature = 32 

if temperature > 32: 
  print("certainly warmer than freezing!")

So if the comparison operator:

  • evaluates to True, then the code inside its indented block gets executed
    • in the example above, the print statement executes
  • evaluates to False, then the code gets skipped

else statements

An else statement has no explicit condition; it simply evaluates the opposite of the condition supplied by the accompanying if statement (an "either/or" structure, when no elif statement exists):

temperature = 32 

if temperature > 32: 
  print("warmer than freezing")
else: 
  print("freezing or colder")

elif statements

The elif statements ("else if" in other languages) number "zero to many" in a branching structure; it provides more variety of scenarios other than "either this or that":

temperature = 52

if temperature > 90:
  print('it is hot')
elif temperature > 70:
  print('it is warm')
elif temperature > 50:
  print('it is mild')
elif temperature > 40: 
  print('it is cool')
else:
  print('it is cold')

If a branching statement (if or elif) evaluates a True, it will execute the branch's indented code block and ignore the rest of the branches ... in the above example, only one statement will print: "it is mild" as the code stops at the "elif temperature > 50:" branch!

⬅️ older (in textbook-python)
🐍 Python operators
newer (in textbook-python) ➡️
Python match + case 🐍
⬅️ older (in code)
🐍 Python operators
newer (in code) ➡️
Python match + case 🐍
⬅️ older (posts)
🐍 Python operators
newer (posts) ➡️
Python match + case 🐍