Booleans

## Description

Programs often rely on conditional logic, such as if statements. To control these functions, there is a special data type, called boolean (abbreviated to bool in Python) which may have only one of two values, true or false. A basic boolean is generated by comparing two values or objects using one of 8 comparators:

• $>$ is >
• $<$ is <
• $\geq$ is >=
• $\leq$ is <=
• $=$ is ==
• $\neq$ is !=
• is tests if two items reference the same object
• is not does the same, but is inverted, similar to == and !=

The is and is not comparators are not often used in the basic Python programming usually seen in Sage, but are included just in case.

## Sage Cell

#### Code

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


#### Boolean Operators

If we want a single boolean value based on multiple conditions, we use one or more of the 3 boolean operators. These operators are

• and: the statement is true if all components are true
• or: the statement is true if one or more components are true
• not: this inverts a statement or component. For example, if a is false, not a is true.

The operators are listed in ascending priority, meaning Sage will evaluate all or operations, then all and operations, then all not operations. All 3 operators have lower priority than the 8 comparators listed above.

#### Code

print(3 < 5 and 5 == 5)
print(3 < 5 and 5 != 5)
print(3 < 5 or 5!= 5)
print(not 5 != 5)


none

## Tags

Primary Tags—Programming: The Python language.

Secondary Tags—The Python language: Expressions and operators.

## Attribute

Permalink:

Author:

Date: 31 Mar 2019 00:14

Submitted by: Zane Corbiere

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License