Python lesson 12

Booleans & Comparisons

Python can decide if something is True or False. And act on it!

True and False. Two Special Values

A boolean is a value that is either True or False. You create booleans by comparing things. The comparison operators are: == (equal to), != (not equal), < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal). These comparisons are used inside if statements to make decisions.

age = 13
print(age >= 13) # True
print(age == 14) # False

age = 13
print(age >= 13)
print(age == 14)

One Equals or Two?

score = 10
print(score == 10)
print(score != 10)
print(score > 10)

Comparing Numbers

Click Run to see how Python evaluates comparisons between two numbers.

Hint: Click Run! Each comparison produces True or False. Try changing a or b to see the results flip.

a = 10
b = 7
print(a == b)
print(a > b)
print(a != b)
print(a <= b)

Even or Odd?

A number is even if the remainder when divided by 2 is 0. Change the number and run to test both even and odd values.

Hint: number % 2 gives the remainder after dividing by 2. If the remainder is 0, the number is even. Try number = 7.

number = 12
if number % 2 == 0:
    print(number, "is even")
else:
    print(number, "is odd")

Score Showdown

Compare two scores and print the right message. Try changing your_score to be lower or higher than top_score!

Hint: Change your_score to 88 to see a tie, or to 80 to see "Top score wins." Each condition uses a comparison operator.

your_score = 95
top_score = 88
if your_score > top_score:
    print("You win!")
elif your_score == top_score:
    print("It's a tie!")
else:
    print("Top score wins.")

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.