g↗genai/ learner
Python for AI / Lesson 07

If-else statements

A program often has to pick one path. An if statement runs a block of code only when a test is true, so the same program can react differently to different inputs.

Concept + interactive labBeginner friendly

If-else statements: Choosing one path.

Each term is defined where it first appears, in this order:

  1. Comparison operators: symbols such as >= (greater than or equal to) and > (greater than) that build a condition.
  2. Condition: a test that gives True or False, such as tokens_left >= 1000. (True and False are Python's two boolean values.)
  3. Branch: the block of lines under one if, elif or else line. Those lines are indented, as the section on colons explains.
  4. if, elif, else: a chain of tests that picks one branch to run. elif is short for "else if".
Running example (invented numbers)

A chat has a limited context window, the amount of text a model can see at once. tokens_left counts how many tokens (pieces of text) are still free. The cut-offs 1000 and 200 are made up for this lesson, and so is the rule that uses them. A real app would weigh more than one number. The cut-offs are not from any real model. For the window itself, see The context window.

One chain, one branch.

Python reads an if, elif, else chain from the top. It runs the first branch whose condition is True, then skips the rest. If no condition is True, the else branch runs. This example ends with an else. A chain without one can run no branch at all when every test is False.

tokens_left = 500
if tokens_left >= 1000:
    action = "send_full_history"
elif tokens_left >= 200:
    action = "send_summary"
else:
    action = "start_new_chat"
print(action)
# send_summary

The first test, 500 >= 1000, is False, so Python moves to the elif. That test is True, so action becomes "send_summary". The else line is skipped.

Flowchart of the chain with two tests and three branches: Start leads to the test 1000 or more. Yes goes to Full history. No goes to the test 200 or more, where Yes goes to Summary and No goes to New chat.
Read the chain left to right. A later test is reached only when the test before it was False.

Everyday analogy: packing a bag for a day out. If it is raining, take an umbrella. Else, if it is hot, take water. Else, take a jacket. You follow one rule and stop, and the rules below it wait their turn.

How to read each line

  • The colon: if, elif and else lines end with a colon (:).
  • The indent: the lines under a line with a colon are indented by four spaces. The examples use four spaces. Lines in one block must share the same indent.
  • elif: a second test. Python checks it only when the first test was False.
  • else: has no condition. It runs when every test above it was False.

The first true test wins.

Only one branch runs, so the order of overlapping tests changes the answer. When the tests are thresholds like these (1000 or more, then 200 or more), put the highest threshold first. A lower threshold placed above it catches values the higher one should handle. The order should follow the priority you want. It is not a general rule for every chain.

tokens_left = 1500
if tokens_left >= 1000:
    action = "send_full_history"
elif tokens_left >= 200:
    action = "send_summary"
else:
    action = "start_new_chat"
print(action)
# send_full_history
tokens_left = 1500
if tokens_left >= 200:
    action = "send_summary"
elif tokens_left >= 1000:
    action = "send_full_history"
else:
    action = "start_new_chat"
print(action)
# send_summary

In the second version, the first test is True for 1500. The elif is never reached, so the output is send_summary, even though 1500 also meets the 1000 rule.

Flowchart with the input 1500 entering the first test 1000 or more, a highlighted path to Full history, and the lower test 200 or more and Summary greyed out as skipped.
Once a test is True, the tests below it are skipped.

Including the boundary: >= and >.

A boundary is the exact number where a rule changes. The operator >= means greater than or equal to, so it is True at the boundary itself. The operator > means strictly greater than, so it is False at the boundary.

print(200 >= 200)   # True
print(200 > 200)    # False
print(199 >= 200)   # False
Number line with a hollow dot at 199 inside the New chat region and a filled dot at 200 at the start of the Summary region.
The rule 200 or more includes the value 200 itself.

Quick check

✎ Try it yourselfKnowledge check · Practice only

Practice: Reading the boundary.

tokens_left = 200 if tokens_left >= 1000: action = "send_full_history" elif tokens_left >= 200: action = "send_summary" else: action = "start_new_chat" print(action) What does the program print?

Colons, indentation and else.

Three details often trip up beginners. Each one is shown in the chain above.

  • A missing colon at the end of an if line raises a SyntaxError.
  • A branch that is not indented raises an IndentationError, because Python cannot tell which lines belong to the branch.
  • = assigns a value, as in action = "x". == compares two values and gives True or False, as in 200 == 200. Use == on an if line.

Quick questions

In an if line, which symbol checks equality: = or ==?
==. A single = assigns a value instead.
Does an else line have a condition?
No. It runs when every test above it was False.
What happens when the lines under an if are not indented?
Python raises IndentationError, because the branch is not marked.
✎ Try it yourselfKnowledge check · Practice only

Practice: Complete the chain.

tokens_left = 350 if tokens_left >= 1000: action = "send_full_history" elif ______: action = "send_summary" else: action = "start_new_chat" Which test goes in place of ______ so that values from 200 to 999 give send_summary?

Try the token budget router.

The slider sets tokens_left. Highlighted lines are the assignment, the print, the tests Python checked, and the branch that ran. Dimmed lines were skipped.

Try it in this order:

  1. Set the slider to 500 and read which branch is highlighted.
  2. Press 1000, then 999. Watch the branch change at the boundary.
  3. Press 200, then 199, and note the change from Summary to New chat.
  4. Press 0. Only the else branch runs.

Toy sandbox: invented values and the same chain as the lesson, not a live Python interpreter. Highlighted lines are the assignment, the print, the tests Python checked, and the branch that ran. Dimmed lines were skipped.

tokens_left = 500if tokens_left >= 1000:    action = "send_full_history"elif tokens_left >= 200:    action = "send_summary"else:    action = "start_new_chat"print(action)
Printedsend_summary
1000 or more? was False, then 200 or more? was True, so the chain stopped there.
✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

tokens_left = 1500 if tokens_left >= 200: action = "send_summary" elif tokens_left >= 1000: action = "send_full_history" else: action = "start_new_chat" print(action) Which line does the program print?
THE TAKEAWAY

Take this with you.

  • One branch: Python runs the first branch whose condition is True. else runs when none is. Without an else, a chain can run nothing.
  • Order: put the strictest test first, or a looser test above it will catch the values it should not.
  • Boundaries: >= includes the number itself. > does not.
  • Syntax: end the line with a colon, indent the branch, and use == to compare.
Back to Chapter P1 →