the full guide

Booleans, comparisons and logic

True and False, comparing values, and combining conditions with and, or, not.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

Questions with a yes or no answer

A comparison asks a question, and Python answers True or False. All decisions in programs, and every “if” in AI code, come down to this.

compare.py
marks = 72

print(marks > 40)     # Greater than
print(marks < 40)     # Less than
print(marks == 72)    # Equal to (two = signs!)
print(marks != 100)   # Not equal to
print(marks >= 72)    # Greater than or equal to

Output

True
False
True
True
True

and, or, not

logic.py
age = 16
has_id = True

print(age >= 18 and has_id)    # Both must be true
print(age >= 18 or has_id)     # One is enough
print(not has_id)              # Flips it

# in checks whether something is inside
print("a" in "apple")
print(3 in [1, 2, 3])

Output

False
True
False
True
True

Shortcuts for updating a value

assign.py
score = 10
score += 5     # Same as score = score + 5
print(score)
score *= 2     # Same as score = score * 2
print(score)
print(2 + 3 * 4)     # Multiply happens first
print((2 + 3) * 4)   # Brackets go first

Output

15
30
14
20

Code challenge

A student passes with 40 or more marks and 75% attendance. Write it for marks = 55, attendance = 70.

print(marks >= 40 and attendance >= 75) gives False, because attendance is short.

Finished reading?