MicroPython Numeric Data Types

Contents

Introduction

MicroPython is a “slim” version of Python specifically designed with a small footprint to efficiently run on memory constrained microcontrollers.

Computer languages have a built-in set of data types along with user capability to define custom types. MicroPython is no exception. Following are the standard or built-in data types of MicroPython:

  • Numeric
  • Boolean
  • Sequence Type
  • Set
  • Dictionary
Python data type hierarchy
Source: geeksforgeeks.org

As shown by this diagram, Python's built-in numeric data types can be categorised into the subtypes:

  • Integer
  • Complex Number
  • Float

The complex number type is of limited use for beginner microcontroller applications and will not be discussed further[1].

Integer

This value is represented by the int class. It contains positive or negative whole numbers (i.e. without fraction or decimal). In MicroPython there is no limit to how long an integer value can be; only being limited by machine memory.

Other languages further break integers down e.g. short integers, positive only integers, long integers and so on. MicroPython does not do this; i.e. int is simply int.

Python provides the built-in function type(). The following program demonstrates MicroPython indeed has only one type of integer (int). Copy the code from this webpage to the Mu Editor, Save and Flash to the micro:bit. Click the REPL button to see the program's output.

Example 1


print("12345 ; type is", type(12345))
print("-12345 ; type is", type(-12345))
print("123456789098765432123456789 ; type is",
       type(123456789098765432123456789))
          

Output:


12345 ; type is <class 'int'>
-12345 ; type is <class 'int'>
123456789098765432123456789 ; type is <class 'int'>
          

Constants

A constant is an identifier with a value that can't be changed. Most modern computer languages provide a mechanism to declare constants. Strangely, Python (and so MicroPython) does not provide a built-in mechanism to do this.

However the standard micropython module[1] does provide a method for defining constants. It has some strict rules around the declaration and unlike other languages, only integers can be declared as constants.

Defining Constants

The micropython.const() method is easy to use. The Official MicroPython documentation recommends it's use as the compiler can use the declaration to make optimisations. The syntax is simple:


Syntax:

import micropython
identifier = const(constant-definition)

Notes:

1 Only integers can be defined as constants,
so constant-definition must evaluate to
type integer.

2 The constant-definition can simply be
an integer. It may be expressed in normal
decimal format eg 19756 or hexadecimal formatting
eg 0xF5 or binary format eg 0b10011101.

3 The const-definition may be an expression
that includes the use of built-in integer
operators and/or other constants that have
already been declared eg: (2024 * 5)
and (CONST1 + 54).

4 The constant-definition must not
contain an expression that uses functions or
methods. The following will cause an error:
(int(CONST1 * 3.1412)).

int() is a function and 3.1412 is type float.

5 The identifier name is capitalised by
convention eg CONST1. Note that this is
only a widely followed convention.
Thus Const1 is perfectly legal but is
'frowned' upon.
          

The following is a simple example of using the const()method:


Example 2

# Demonstrates the declaration of
# constants in MicroPython.

from micropython import const

# Declare some constants
FRED = const(579)
CAVE = const(12)
SITE = const(FRED * CAVE)
BIN = const(0b10011101)
HEX = const(0xF5)

# Show their values.
print('FRED =', FRED)
print('CAVE =', CAVE)
print('SITE =', SITE)
print('BIN =', BIN)
print('HEX =', HEX)
          

Output:

FRED = 579
CAVE = 12
SITE = 6948
BIN = 157
HEX = 245
          

Note that the binary and hexadecimal formatted integer constants are printed in standard decimal number format. MicroPython will always do this unless the conversion functions bin() and hex() respectively are explicitly used.

Why Use Constants?

The most common use for constants is in device driver code. For example, many sensors have a register that a command is sent to, then one or more data registers are read to obtain the measured value. It is convention and very good practice to declare the address of these registers as constants at the top of the driver code. For example:


REG_CONFIG = 0x00
REG_CMD = 0x01
REG_PRESSURE = 0x80
REG_HUMIDITY = 0x82
          

By convention the addresses are usually expressed in hexadecimal because that's the usual way they are shown in the datasheet.

Float

This value is represented by the float class. It is a real number with floating point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation; e.g. 245.0 can be represented as 2.45E2

Try the following program in the micro:bit using the Mu Editor:

Example 3


print("12345.98 ; type is", type(12345.98))
print("-12345.98 ; type is", type(-12345.98))
print("12. ; type is", type(12.))
print("23e2 ; type is", type(23e2))
print("5.97E-200 ; type is", type(5.97E-200))
          

Output:


12345.98 ; type is <class 'float'>
-12345.98 ; type is <class 'float'>
12. ; type is <class 'float'>
23e2 ; type is <class 'float'>
5.97E-200 ; type is <class 'float'>

Type Conversions

There are two types of Type Conversion in MicroPython:

  1. Implicit Type Conversion
  2. Explicit Type Conversion

In Implicit Type Conversion the MicroPython interpreter automatically converts one data type to another without any user involvement. This occurs when an expression has a mixture of different types. For example, an expression with a mix of integer and float will produce a result of type float. This ensures no loss of information as float is the wider-sized type.

The following program demonstrates this concept.

Example 4


a = 5
b = 21.3
c = a + b
print("a =", a, " ; Type is:", type(a))
print("b =", b, " ; Type is:", type(b))
print("c =", c, " ; Type is:", type(c))
          

Output:


a = 5  ; Type is: <class 'int'>
b = 21.3  ; Type is: <class 'float'>
c = 26.3  ; Type is: <class 'float'>

In the above example the variable a is implicitly converted from int to float. The variable c becomes type float.

In an Explicit Type Conversion the data type is changed by the user. There is a risk of data loss such as when a float is explicitly changed to an integer.

⇒ The function int() converts other data types to integer.

⇒ The function float() converts other data types to float.

The following small program demonstrates this.

Example 5


a = 5.9
b = 21.3

c = int(a + b)
print("c =", c, "; type(c) is ", type(c))

d = int(a) + int(b)
print("d =", d, "; type(d) is ", type(d))

print("float(5) =", float(5))
          

Output:


c = 27 ; type(c) is  <class 'int'>
d = 26 ; type(d) is  <class 'int'>
float(5) = 5.0

          

Code Explanation

c = int(a + b)
  = int(5.9 + 21.3)
  = int(27.2)
  = 27

d = int(a) + int(b)
  = int(5.9) + int(21.3)
  = 5 + 21
  = 26
            

It's sometimes necessary to explicitly use int() or float() to prevent an error from occurring. Consider the following examples:


5 + '6'  ⇒ TypeError: unsupported types for __add__: 'int', 'str'
5 + int('6') ⇒ 11

3.4567 * '45.87' ⇒ TypeError: unsupported types for : 'float', 'str'
3.4567 * float('45.87') ⇒  158.558