Python for Artificial Intelligence Beginner 10 minutes

Conditions

How does a program make decisions with if, elif and else?

Your progress in the track0%

The basic structure

score = 75
if score >= 90:
    grade = "Excellent"
elif score >= 70:
    grade = "Good"
else:
    grade = "Needs review"
print(grade)   # Good

The conditions are evaluated from top to bottom, and only the first true branch runs.

Compound conditions

age, has_id = 20, True
if age >= 18 and has_id:
    print("Allowed")

Implicitly true and false values

The condition does not have to be an explicit comparison:

data = []
if not data:
    print("No data")

Implicitly false values: False, None, 0, 0.0, "", [], {}, set(). Everything else counts as true.

A one-line conditional expression

label = "positive" if prob >= 0.5 else "negative"

This form is useful for turning a probability produced by a classification model into a class using a threshold.

Common mistakes

  • Forgetting the colon : at the end of the condition line.
  • Using = instead of == in a comparison.
  • Inconsistent indentation between lines within the same branch.

Lesson terms

Conditional statement
A construct that executes a block of code only when a logical condition is true.
Falsy values
Values treated as False in conditions, such as 0, "", [] and None.

Abstract

The conditional statements if, elif and else allow different parts of the code to run depending on the value of a Boolean condition. The conditions are evaluated in order and only the first true branch runs, and Python treats values such as 0, the empty string, the empty list and None as false (falsy).

Review questions

  1. How many branches run in an if/elif/else chain?

    At most one: the first branch whose condition holds, or else if no condition holds.

  2. Is an empty list true or false in a condition?

    False (falsy).

Sources and references

  1. More Control Flow Tools: if Statements — Python documentation
  2. Truth Value Testing — Python documentation

Complete the lesson