The unofficial CircuitPython Reference

logical expressions

description

Logical expressions (also known as boolean expressions) are a primary means of controlling the flow of code and making decisions in Python and programming in general. In Python these expressions result in either True or False values that are generally used in conditional statements to 'decide' whether or not to execute nested code blocks. Logical operators and or not in conjunction with comparisons between values are the building blocks of logical expressions.

syntax

and

(expression1) and (expression2)

The and operator will exclusively combine two or more comparison expressions together into a compound logical expression that results in a True value if and only if ALL statements are True. The resulting expression is therefore more exclusive than a single comparison because all comparisons must evaluate True for the entire expression to evaluate True.

Example:

a = 0
b = -1
c = 10

(b > a) and (b < c)

False AND True is False

or

(expression1) or (expression2)

The or operator will inclusively combine two or more comparison expressions together into a compound logical expression that results in a True value if and only if ANY statements are True. The resulting expression is therefore more inclusive than a single comparison because any True comparison will allow the entire expression to evaluate True.

Example:

a = 0
b = -1
c = 10

(b > a) or (b < c)

False OR True is True

not

not expression1

The not operator will negate any expression so that the resulting expression evaluates True when the original expression is False and evaluates False when the original expression is True. This operator is a single argument operator and simply reverses the boolean (true/false) value of a given expression.

Example:

a = False

not (a)

NOT False is True

methods

parameters

and / or

expression1 : any boolean (true / false) expression

expression2 : any boolean (true / false) expression

Example:

True is a boolean expression

False is a boolean expression

a < b is a boolean expression

button_a.value is a boolean expression (True when pressed, false when not pressed)

not

expression1 : any boolean (true / false) expression

returns

and / or

A boolean (true / false) expression

not

A boolean (true / false) expression

example code

serial output:

see also: