Learn Python · lesson 11 of 60 · about 7 minutes
Booleans and Comparisons
Let the assistant answer yes-or-no questions: compare values to get True or False, and combine answers with and, or and not.
What you'll learn
- Use True and False
- Compare values with == != < > <= >=
- Combine conditions with and, or, not
Yes-or-no questions
Is there enough for the bike yet? A comparison answers a question like that with a boolean: True or False, each with a capital letter.
| Operator | Asks |
|---|---|
| == | equal? |
| != | not equal? |
| < > | less, more? |
| <= >= | at most, at least? |
== compares two values. A single = stores a value.
Comparisons give True or False
saved = 45
price = 120
print(saved >= price)
print(saved != 0)
print("bike" == "Bike")Output
False
True
Falseand, or, not
andis True only when both sides are Trueoris True when at least one side is Truenotflips True and False
not goes first, then and, then or. Brackets make the order obvious. Python also lets you chain comparisons: 11 <= age <= 16 checks both at once.
Should Sam take an umbrella?
rain = 70
staying_in = False
print(rain >= 50 and not staying_in)
print(rain >= 90 or staying_in)Output
True
FalseTip
Comparing text is exact: capitals and spaces count. Tidy text with strip() and lower() before you compare it.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.