Booleans and Comparisons

Booleans and Comparisons

A boolean is a value that is either True or False. Both are written with a capital first letter and no quotes.

Comparison operators produce booleans:

print(3 < 5)
print(3 > 5)
print(3 == 3)
print(3 != 3)

Output:

True
False
True
False

The six comparison operators:

  • == equal to
  • != not equal to
  • < less than
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to

== compares; = assigns. Writing if x = 3 instead of if x == 3 is a syntax error.

Comparisons work on strings too: "Ada" == "Ada" is True, and "Ada" == "ada" is False — case counts.

A comparison is a value like any other. It can be stored or returned:

def is_adult(age):
    return age >= 18

print(is_adult(20))

Output:

True

Exercise

  1. Define a function named is_freezing with one parameter, celsius. It returns True when celsius is at or below 0, otherwise False.
  2. Return the comparison directly — the body needs one line.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestIsFreezing(unittest.TestCase):
    def test_minus_5_is_freezing(self):
        self.assertIs(is_freezing(-5), True)

    def test_10_is_not_freezing(self):
        self.assertIs(is_freezing(10), False)

    def test_exactly_0_is_freezing(self):
        self.assertIs(is_freezing(0), True)
def is_freezing(celsius):
    return celsius <= 0


print(is_freezing(-5))
print(is_freezing(10))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.