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.
A Boolean is a data type that can only be True or False. We often get Booleans by comparing values:
== (e.g., 5 == 5 is True)!=>, <>=, <=if StatementAn if statement checks a condition. If the condition is True, it runs the code block indented underneath it.
else and elifWe can chain conditions to handle multiple possibilities.
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.
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.
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.
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 -> spamThe 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.
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.
if x = 5: is a SyntaxError; you want ==.0.1 + 0.2 == 0.3 is False because of binary rounding. Compare with a tolerance, or use abs(a - b) < 1e-9.(x == 1) or 2, which is always truthy. Write x == 1 or x == 2, or x in (1, 2).and, or, not combine conditions and short-circuit.Before machine learning, early AI used "expert systems" that relied on hard-coded rules. Let's build a simple rule-based spam detector!
email_text and assign it a string containing the words "free money" and "click here".if statement that checks if "free money" in email_text and "click here" in email_text.print("SPAM DETECTED").print("Not spam").Hint: You can use the and keyword to combine two conditions.