Know some Python? Write your own interactive tutorial, with runnable examples and exercises, and share it with a link. Write and share your own tutorial.

Start writing

Learn Python / Booleans and Comparisons

Booleans and Comparisons

Programs constantly ask yes-or-no questions: Is the password correct? Is the user old enough? Is the cart empty? In Python, the answer to such a question is a boolean: either True or False.

True and False

True and False are values of type bool. Note the capital letters: true and TRUE are just unknown names, and give a NameError. Don't put them in quotes either. "True" is a string, not a boolean.

is_raining = True
has_umbrella = False

print(is_raining)
print(type(has_umbrella))
Output

Comparison operators

Comparison operators compare two values and give back True or False:

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
< Less than 3 < 5 True
> Greater than 3 > 5 False
<= Less than or equal to 5 <= 5 True
>= Greater than or equal to 4 >= 5 False
age = 17

print(age == 18)
print(age != 18)
print(age < 18)
print(age >= 18)
Output

Watch out: = assigns a value, while == compares two values. Mixing them up is one of the most common beginner mistakes.

Comparing values of different types needs care, especially with input, which is always text:

Comparison Result Why
5 == 5.0 True an int and a float compare by value
5 == "5" False a number is never equal to a string, even if it looks the same
5 < "10" TypeError Python can't order a number and a string

So convert input with int() or float() before comparing it to a number.

You can store the result of a comparison in a variable:

age = 20
is_adult = age >= 18
print(is_adult)
Output

Chaining comparisons

Python lets you chain comparisons the way you would in maths:

temperature = 22

# is it between 18 and 25?
print(18 <= temperature <= 25)
print(0 < temperature < 10)
Output

18 <= temperature <= 25 means exactly the same as 18 <= temperature and temperature <= 25 (you'll meet and below). It's True only when both parts are true.

Comparing strings

Strings can be compared too. == checks for an exact match, and it's case-sensitive:

print("python" == "python")
print("Python" == "python")
print("python" == "Python".lower())
Output
Going deeper: Comparing text with < and > optional

< and > compare strings alphabetically, character by character. One surprise: all capital letters come before all lowercase letters, so "Zebra" comes before "apple":

print("apple" < "banana")
print("cat" > "car")
print("Zebra" < "apple")
Output

Convert both sides with .lower() first if you want a true alphabetical comparison.

Going deeper: Comparing decimal numbers optional

Because floats aren't always exact (remember 0.1 + 0.2 from the Numbers and Math lesson?), comparing them with == can surprise you. The math module has isclose(), which checks whether two numbers are close enough:

import math

print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
Output

Logical operators: and, or, not

Combine several conditions with and, or and not:

  • a and b is True only if both are True.
  • a or b is True if at least one is True.
  • not a flips True to False and back.
age = 25
has_ticket = True

# both are true
print(age >= 18 and has_ticket)

# neither is true
print(age < 12 or age > 65)

print(not has_ticket)
Output

Here's how they work for every combination:

a b a and b a or b not a
True True True True False
True False False True False
False True False True True
False False False False True

Watch out: each side of and / or must be a complete condition. In English you might say "x is 1 or 2", but in Python x == 1 or 2 doesn't do that. It means (x == 1) or 2, and 2 on its own counts as true (see Truthiness below), so the result is never False. Write x == 1 or x == 2. Likewise, age > 12 and < 20 is a SyntaxError; write age > 12 and age < 20, or 12 < age < 20.

When you mix them, not is applied first, then and, then or. Use parentheses to make longer conditions easy to read:

is_weekend = True
is_holiday = False
is_raining = True

go_to_park = (is_weekend or is_holiday) and not is_raining
print(go_to_park)
Output

Python works it out in steps:

  1. The parentheses first: is_weekend or is_holiday is True or False, which is True.
  2. not is_raining is not True, which is False.
  3. Finally True and False, which is False. No park today.

Truthiness

Python can treat any value as true or false. Use bool() to see how a value is treated:

print(bool(0))       # False
print(bool(42))      # True
print(bool(""))      # False: empty string
print(bool("hi"))    # True
print(bool(None))    # False
print(bool(0.0))     # False
Output

The rule is simple. Zero, empty values and None are "falsy", which just means Python treats them like False. Almost everything else is "truthy", treated like True.

Falsy (treated as False) Truthy (treated as True)
False True
0 and 0.0 any other number, including negatives like -1
"" (an empty string) any non-empty string, even " " or "False"
None

Watch the strings: only a string with nothing in it is falsy. A single space, "0" and "False" all contain characters, so they're truthy. This becomes very handy with if statements in the next lesson.

Going deeper: Booleans are numbers too optional

Under the hood, True behaves like 1 and False like 0. That lets you count how many conditions are true by adding them up:

passed_math = True
passed_science = False
passed_english = True

print(passed_math + passed_science + passed_english)
Output
Going deeper: Checking for None with is optional

To check whether a variable holds None, Python programmers write is None rather than == None:

result = None

print(result is None)
print(result is not None)
Output

== asks "do these have the same value?", while is asks "are these the very same object?". There's only ever one None, so is is the precise way to check for it. You'll see is None in later lessons, for example in Function Arguments.

Use is only for None. For numbers, strings and everything else, compare values with ==.

Exercises

Exercise 1: Voting age

Print True if age is 18 or over, otherwise False. Try changing age to check both cases.

age = 16
Output

Exercise 2: In range

Print True if score is between 0 and 100 (inclusive). Use a chained comparison.

score = 87
Output

Exercise 3: Login check

A login succeeds when the username is "admin" and the password is "secret123". Print whether the login succeeds. The username check should ignore capital letters.

username = "Admin"
password = "secret123"
Output

Exercise 4: Predict the output

Before you run this, predict what each line prints. Then run it to check.

print(10 > 5 and 3 > 7)
print(10 > 5 or 3 > 7)
print(not 10 > 5)
print(bool("False"))
print("abc" == "ABC".lower())
Output

Summary

  • A boolean is True or False, and its type is bool.
  • Comparison operators ==, !=, <, >, <= and >= produce booleans. Don't confuse == with =.
  • Comparisons can be chained: 0 <= x <= 100.
  • and, or and not combine conditions. Use parentheses for clarity.
  • Zero, empty strings and None are falsy. Most other values are truthy.

Share this tutorial

Know something worth teaching? Write your own tutorial with runnable examples and share it.