Introduction to Python Resources

Begin your free Python journey now,
at your own pace

check

Concepts: Booleans

check

Representing on/off, yes/no, and true/false values with Python booleans.


Booleans in Python

A "boolean" is a type of data that can only have two possible values. Conceptually, many things can be reduced to a pair of possibilities:

  • yes / no
  • on / off
  • true / false
  • selected / not selected
  • moving / not moving
  • heads / tails

Python represents booleans with two values: True and False. Comparison operations in Python result in a boolean value being returned.

The most common comparison operation is checking for equality using the equality operator (==). The equality operator checks if the values to the left and right of it are equal to each other.

After the comparison is done, a True value is returned if the two values being compared are the same and False if they are not:

Note the examples below:

print(2 == 2)

> True

print(2 == 7)

> False

print(13.66 == 13.66)

> True

print("Hello" == "Hello")

> True

print("Hello" == "Hi")

> False

Practice: Booleans

Based on the information above. Complete the following steps:

  1. Create a variable named does_string_equal_number and assign it the result of comparing the number value 5 with the string value "5".

  2. Print the boolean value in the does_string_equal_number variable.

  3. Create a variable named do_numbers_match and assign it the result of comparing the number value 5 and the number value 5.

  4. Print the boolean value in the do_numbers_match variable.

  5. Create a variable named does_casing_match and assign it the result of comparing the string value "Hello" and the string value "hello".

  6. Print the boolean value in the does_casing_match variable.

    HINT*: Click here for a hint
    *Hints are best viewed after completing a task, or after spending some time and effort attempting it. In cases where a hint contains example output, it is important to understand why it is correct, as there may be many correct outputs.
    > False
    > True
    > False
    SOLUTION*: Click here for an example solution
    *Example solutions are best viewed after completing a task and understanding the outcome. In most cases, there are multiple ways to complete a task, and the example solution is only one example.
    does_string_equal_number = 5 == "5"
    print(does_string_equal_number)
    do_numbers_match = 5 == 5
    print(do_numbers_match)
    does_casing_match = "Hello" == "hello"
    print(does_casing_match)
    

When you have completed the above and understand that boolean values are returned from comparison operations, you are ready to go to the next exercise!