Lesson 6: Making Decisions — Conditionals

Use if, elif, else statements; understand comparison and logical operators.

By • Last updated • 50 min

AI models don't just crunch numbers; they use them to make decisions. Let's learn how to do that in Python.

In programming, decisions are made using conditionals: statements like if, elif (else if), and else. They allow our code to react differently depending on the data it receives.

Booleans and Comparisons

A Boolean is a data type that can only be True or False. We often get Booleans by comparing values:

  • Equals: == (e.g., 5 == 5 is True)
  • Not Equals: !=
  • Greater/Less Than: >, <
  • Greater/Less Than or Equal To: >=, <=

The if Statement

An if statement checks a condition. If the condition is True, it runs the code block indented underneath it.

accuracy = 0.92
if accuracy > 0.90:
    print("Excellent model!")

Adding else and elif

We can chain conditions to handle multiple possibilities.

if accuracy > 0.90:
    print("Excellent")
elif accuracy > 0.75:
    print("Good")
else:
    print("Needs improvement")

Indentation Is the Syntax

Most languages use braces to mark a block of code. Python uses indentation. Every line indented under an if belongs to that branch, and the block ends when the indentation returns to the previous level. The convention is four spaces. Mixing tabs and spaces, or indenting one line of a block differently from its neighbours, produces an IndentationError. The colon at the end of the if line is also required; forgetting it is one of the most common typos.

How elif Chains Are Evaluated

An if / elif / else chain is checked top to bottom, and only the first branch whose condition is True runs. The rest are skipped, even if they would also be true. That makes the order of your conditions part of the logic. Consider grading a model:

accuracy = 0.92

if accuracy > 0.75:
    print("Good")
elif accuracy > 0.90:
    print("Excellent")     # never reached!
else:
    print("Needs improvement")

With an accuracy of 0.92 this prints "Good", because the first test already succeeded. The fix is to put the strictest condition first, exactly as the lesson example did. Whenever your conditions overlap, order them from most specific to least specific.

Combining Conditions: and, or, not

Real decisions rarely depend on one fact. Python's logical operators combine Boolean values:

  • a and b is True only when both are True.
  • a or b is True when at least one is True.
  • not a flips True to False and the reverse.

Python evaluates and and or lazily: in a and b, if a is False then b is never even checked. You can rely on this to guard risky expressions, for example total > 0 and correct / total > 0.9 never divides by zero. Python also allows chained comparisons, so 0.0 <= p <= 1.0 reads exactly like the maths and checks that a probability is valid.

Worked Example: Turning a Probability into a Label

Almost every classifier outputs a probability, and your code must turn it into a decision. This is a conditional with a threshold:

probability_spam = 0.83
threshold = 0.5

if probability_spam >= threshold:
    label = "spam"
else:
    label = "not spam"

print(f"P(spam)={probability_spam:.2f} -> {label}")
# P(spam)=0.83 -> spam

The threshold is a design decision. Lowering it to 0.3 catches more spam but also flags more legitimate email. You will study exactly this trade-off, precision against recall, when you evaluate classifiers later in the course.

Truthiness and the in Operator

Python lets you use non-Boolean values as conditions. Empty things are treated as False: the empty string "", the number 0, and the empty list []. Everything else is True. So if email_text: means "if the text is not empty". The in operator, used in the challenge below, tests membership: "free" in "get free money" is True because the substring appears. Note that it is case sensitive, so lowercase the text with .lower()first if you want to match "FREE" too.

Common Pitfalls

  • Using = inside a condition. if x = 5: is a SyntaxError; you want ==.
  • Comparing floats for exact equality. 0.1 + 0.2 == 0.3 is False because of binary rounding. Compare with a tolerance, or use abs(a - b) < 1e-9.
  • Writing x == 1 or 2. This does not mean "x is 1 or 2"; it is parsed as (x == 1) or 2, which is always truthy. Write x == 1 or x == 2, or x in (1, 2).
  • Overlapping elif ranges in the wrong order, as shown above.

Recap

  • Conditions evaluate to True or False; comparison operators produce them.
  • Indentation defines which lines belong to a branch.
  • An if/elif/else chain runs only the first matching branch, so order matters.
  • and, or, not combine conditions and short-circuit.
  • Thresholding a probability is the bridge from model output to a decision.

Coding Challenge: Rule-Based Classifier

Before machine learning, early AI used "expert systems" that relied on hard-coded rules. Let's build a simple rule-based spam detector!

  1. Create a variable email_text and assign it a string containing the words "free money" and "click here".
  2. Write an if statement that checks if "free money" in email_text and "click here" in email_text.
  3. If both conditions are true, print("SPAM DETECTED").
  4. Otherwise, print("Not spam").

Hint: You can use the and keyword to combine two conditions.

main.py
Run your code to see output here.