2.1 Relational and Logical Operators
Programs do not only run statements in order. They often need to check whether a condition is true, then choose what to do next. A condition usually produces a Boolean value: True or False.
Relational operators
Relational operators compare two values. The result of a comparison is a Boolean value, not another number.
Common Python relational operators:
<: less than>: greater than<=: less than or equal to>=: greater than or equal to==: equal to!=: not equal to
Important: one equals sign = means assignment. Two equals signs == mean comparison.
age = 17
print(age < 18) # True
print(age == 18) # False
print(age != 18) # Trueage = 17 stores 17 in the variable age. age == 18 checks whether the current value of age equals 18.
Logical operators
Logical operators combine multiple conditions. Their result is still a Boolean value.
and: the whole expression isTrueonly when every condition isTrue.or: the whole expression isTruewhen at least one condition isTrue.not: turnsTrueintoFalse, andFalseintoTrue.
age = 20
has_ticket = True
print(age >= 18 and has_ticket) # True
print(age < 18 or has_ticket) # True
print(not has_ticket) # FalseIt helps to read conditions like plain language: age >= 18 and has_ticket means “the age is at least 18, and the person has a ticket.”
Combining conditions
Python supports chained comparisons:
age = 16
print(0 < age < 18) # TrueThis is equivalent to:
print(0 < age and age < 18)When a condition becomes complex, use parentheses or meaningful variable names to keep the logic readable.
score = 85
attendance = 92
passed = score >= 60 and attendance >= 80
excellent = score >= 90 or attendance >= 95
print(passed) # True
print(excellent) # FalseDo not rush to squeeze every condition into one line. Naming smaller conditions makes the program easier to read and debug.