Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

4.1 Boolean values

Learning objectives

By the end of this section you should be able to

  • Explain a Boolean value.
  • Use bool variables to store Boolean values.
  • Demonstrate converting integers, floats, and strings to Booleans.
  • Demonstrate converting Booleans to integers, floats, and strings.
  • Use comparison operators to compare integers, floats, and strings.

bool data type

People often ask binary questions such as yes/no or true/false questions. Ex: Do you like pineapple on pizza? Ex: True or false: I like pineapple on pizza. The response is a Boolean value, meaning the value is either true or false. The bool data type, standing for Boolean, represents a binary value of either true or false. true and false are keywords, and capitalization is required.

Type conversion with bool

Deciding whether a value is true or false is helpful when writing programs/statements based on decisions. Converting data types to Booleans can seem unintuitive at first. Ex: Is "ice cream" True? But the conversion is actually simple.

bool converts a value to a Boolean value, True or False.

  • True: any non-zero number, any non-empty string
  • False: 0, empty string

Comparison operators

Programmers often have to answer questions like "Is the current user the admin?" A programmer may want to compare a string variable, user, to the string, "admin". Comparison operators are used to compare values, and the result is either true or false. Ex: is_admin = (user == "admin"). user is compared with "admin" using the == operator, which tests for equality. The Boolean variable, is_admin, is assigned with the Boolean result.

The 6 comparison operators:

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

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.