MicroPython Comparison and Logical Operators

Contents

Introduction

Operators are an essential part of just about any computing language ever devised and MicroPython is of no exception. The MicroPython operators can be broadly classified into eight groups:

  1. Arithmetic
    - , + , * , / , % , ** , //
  2. Assignment
    = , augmented assignments e.g. +=
  3. Comparison
    == , != , > , < , >= , <=
  4. Logical
    and , or , not
  5. Identity
    is , is not
  6. Membership
    in , not in
  7. Bitwise
    & , ! , ^ , ~ , << , >>
  8. Unpacking Operators
    * , **

Comparison Operators

All six comparison operators available in Python are also found in MicroPython.

Table 1: MicroPython Comparison Operators
Operator Description
==

Equal

x, y = 5, 5
x == y ⇒ True

!=

Not Equal

x, y = 5, 5
x != y ⇒ False

>

Greater Than

x, y = 6, 5
x > y ⇒ True

<

Less Than

x, y = 6, 5
x < y ⇒ False

>=

Greater Than or Equal To

x, y = 6, 5
x >= y ⇒ True

x, y = 6, 6
x >= y ⇒ True

<=

Less Than or Equal To

x, y = 6, 5
x <= y ⇒ False

x, y = 6, 6
x <= y ⇒ True

Logical Operators

Logical operators are used to combine conditional statements containing comparison operators. MicroPython has only three logical operators.

Table 2: MicroPython Logical Operators
Operator Description
and

(Statement 1) and (statement 2)
Returns True if both statements are true

x, y = 5, 6
(x == 5) and (y == 7) ⇒ False

or

(Statement 1) or (statement 2)
Returns True if either statements is true

x, y = 5, 6
(x == 5) or (y == 7) ⇒ True

not

Reverses the result;
returns False if the result is True
returns True if the result is False

x, y = 5, 6
not((x == 5) and (y == 7)) ⇒ True
not((x == 5) or (y == 7)) ⇒ False