MicroPython Built-in Functions
Contents
Introduction
MicroPython is a “slim” version of Python specifically designed with a small footprint to efficiently run on memory constrained microcontrollers.
MicroPython does not implement the complete complement of Python built-in functions. This tutorial describes only those built-ins that are supported by MicroPython. All code examples are original and have been tested on a micro:bit for correctness using the Mu Editor.
An exhaustive alphabetic list of MicroPython functions with a brief description appears in the following table. Each function name has a link to a deeper description, complete with examples.
This is a lengthy article so hyperlinks are provided regularly through the page to aid navigation.
Built-in Function List
Function | Description |
---|---|
abs() | Returns the absolute value of a number |
all() | Returns True if all items in an iterable object are true |
any() | Returns True if any item in an iterable object is true |
bin() | Returns the binary version of a number |
bool() | Returns the boolean value of the specified object |
bytearray() | Returns an array of bytes |
bytes() | Returns a bytes object |
callable() | Returns True if the specified object is callable, otherwise False |
chr() | Returns a character from the specified Unicode code, in the range 0..255 |
classmethod() | Converts a function into a class method |
complex() | Returns a complex number |
delattr() | Deletes the specified attribute (property or method) from the specified object |
dict() | Returns a dictionary (Array) |
dir() | Returns a list of the specified object's properties and methods |
divmod() | Returns the quotient and the remainder when argument1 is divided by argument2 |
enumerate() | Takes a collection (e.g. a tuple) and returns it as an enumerate object |
eval() | Evaluates and executes an expression |
exec() | Executes the specified code (or object) |
filter() | Use a filter function to exclude items in an iterable object |
float() | Returns a floating point number |
getattr() | Returns the value of the specified attribute (property or method) |
globals() | Returns the current global symbol table as a dictionary |
hasattr() | Returns True if the specified object has the specified attribute (property/method) |
hash() | Returns the hash value of a specified object |
help() | Executes the built-in help system |
hex() | Converts a number into a hexadecimal value |
id() | Returns the id of an object |
input() | Allowing user input |
int() | Returns an integer number |
isinstance() | Returns True if a specified object is an instance of a specified object |
issubclass() | Returns True if a specified class is a subclass of a specified object |
iter() | Returns an iterator object |
len() | Returns the length of an object |
list() | Returns a list |
locals() | Returns an updated dictionary of the current local symbol table |
map() | Returns the specified iterator with the specified function applied to each item |
max() | Returns the largest item in an iterable |
memoryview() | Returns a memory view object |
min() | Returns the smallest item in an iterable |
next() | Returns the next item in an iterable |
object() | Returns a new object |
oct() | Converts a number into an octal |
open() | Opens a file and returns a file object |
ord() | Convert an integer representing the Unicode of the specified character |
pow() | Returns the value of x to the power of y |
print() | Prints to the standard output device |
property() | Gets, sets, deletes a property |
range() | Returns a sequence of numbers, starting from 0 and increments by 1 (by default) |
repr() | Return a string containing a printable representation of an object |
reversed() | Returns a reversed iterator |
round() | Rounds a numbers |
set() | Returns a new set object |
setattr() | Sets an attribute (property/method) of an object |
sorted() | Returns a sorted list |
staticmethod() | Converts a method into a static method |
str() | Returns a string object |
sum() | Sums the items of an iterator |
super() | Returns an object that represents the parent class |
tuple() | Returns a tuple object |
type() | Returns the type of an object |
zip() | Returns an iterator, from two or more iterators |
Detailed Function Description
abs()
Syntaxabs(<num>)
Description
Returns the absolute value of the given float or integer number.
‘The absolute value of a number may be thought of as its distance from zero’ [1].
In practical terms this generally means removing a negative sign if the number is negative.
If the number is a complex number the magnitude is returned.
Example 1
# Demonstrates the built-in function abs()
list1 = [3, -99, 0, -5.81, 3 + 4j]
for num in list1:
print('abs(', num, ') =', abs(num))
Output:
abs( 3 ) = 3 abs( -99 ) = 99 abs( 0 ) = 0 abs( -5.81 ) = 5.81 abs( (3+4j) ) = 5.0
The last one deserves some further explanation. The (3+4j) is a complex number, composed of a real component and an imaginary component. Python is one of very few computer languages that natively provide a complex number type.
Complex numbers have many uses in applied mathematics. They are often used to manipulate GPS coordinates eg the GPS coordinates of the Sydney Harbour Bridge, 33.8523° S, 151.2108° E could be represented by the complex number -33.8523 + 151.2108j.
Unfortunately, MicroPython doesn't come with the cmath library of Python. However the built-in complex number functionality of MicroPython can be suitably used to manipulate GPS data that a microcontroller is reading in realtime from a GPS chip.
Consider the complex number 3 + 4j as the coordinate on a two dimensional cartesian plane where the point is located 3 units in the x direction and 4 units in the y direction. The function abs(3 + 4j) is the distance from the point to the origin (0,0); in this case 5 units.
Back to function listall()
Syntaxall(<iterable>)
Description
Returns True if all elements in the given iterable are true. If not, it returns False.
Related functions
Example 2
# Simple demonstration of the
# built-in function all()
list1 = [True, True, True]
list2 = [True, False, True]
print('all(list1) =', all(list1))
print('all(list2) =', all(list2))
Output:
all(list1) = True all(list2) = FalseExample 3
# More complex demonstration
# of the built-in function all()
# This program has a dataset that
# contains two lists.
# If all elements of a list are
# numerical the average value is calculated.
# If a list contains any elements that aren't
# numerical an error is reported.
# Function to check whether a list contains
# all numericals.
def isnumbers(values):
list1 = []
for value in values:
# Is value an integer?
isint = type(value)==int
# Is value a float?
isfloat = type(value)==float
# If value is an integer or a float
# then it is numerical
isnum = isint or isfloat
list1.append(isnum)
# if all values are numerical then
# True will be returned else False.
return all(list1)
# Function calculates average value
# of a list of verified numbers.
def average(values):
total = sum(values)
count = len(values)
return total / count
# Set containing two lists.
dataset = ([5, 9, 1, 0], [5, 9, 1, 0, 'spam'])
# Process each list and attempt to
# calculate an average value.
for data in dataset:
if isnumbers(data):
# The list is all numerical
print(data, ': average =', average(data))
else:
# The list contains non-numerical values.
print(data,': Nonnumerical data in list')
Output:
[5, 9, 1, 0] : average = 3.75 [5, 9, 1, 0, 'spam'] : Nonnumerical data in list
This example uses all() to check that all values in a dataset are numerical before calculating the average.
Back to function listany()
Syntaxany(<iterable>)
Description
Returns True if any element of an iterable is True. If not, it returns False.
Related functions
Example 4
# Simple demonstration of the
# built-in function any()
list1 = [False, True, True]
list2 = [False, False, False]
list3 = [True, True, True]
print('any(list1) =', any(list1))
print('any(list2) =', any(list2))
print('any(list3) =', any(list3))
Output:
any(list1) = True any(list2) = False any(list3) = True
The next example is specifically written for the micro:bit. It is a simulation where the microcontroller polls five status panels, each with five status indicators (LEDs) of a running machine and reacts to any status change.
Copy the code to the Mu Editor, save and flash to the micro:bit. Wait for around a minute before accessing the REPL to see the output.
Example 5
# A more complex demonstration of
# the built-in function any().
# This program simulates a microcontroller
# monitoring status of five instrument panels.
# The panels are labelled panel 1 to panel 5.
# Each panel contains five LED status lights.
# Once every five seconds each panel is read
# by the microcontroller. If a panel has at
# least one LED ON then that panel must
# be serviced and reset.
# This cycle of reading, checking, servicing
# and resetting panels continues on in an
# endless loop, till the machine is stopped.
# It is known that there is a 5% chance that
# at least one LED on a panel will be found ON
# at each read.
# For the purpose of this realtime simulation,
# random numbers will be used to set
# LEDs ON or OFF.
# Generates random integers
import random
# Provides timing functions
import time
# Function to 'read' a status panel
# There is a 20% chance that at least
# one LED will be ON.
def read_panel(panel):
panel = [] # Reset the panel
for i in range(1, 6):
if (random.randint(1, 20) != 20):
# LED is OFF
panel.append(False)
else:
# LED is ON
panel.append(True)
return panel
def service_panel(panel):
pass # Do some things!
# Returns the machine uptime in seconds
def uptime():
now = time.ticks_ms()
tdiff = time.ticks_diff(now, begin)/1000
return tdiff
# The five panels are implemented as
# a list of lists, each of the nested
# representing one panel.
panels = [[], [], [], [], []]
# Start the machine's clock.
begin = time.ticks_ms()
finished = False
print('Starting machine monitoring...')
# Wait 10 seconds for the machine
# to fully start up.
time.sleep_ms(10000)
# Main program is an endless loop
while not(finished):
counter = 1
# Cycle through each of the
# five panels in turn.
for panel in panels:
panel = read_panel(panel)
if any(panel):
# At least one LED is ON
# Print the status of the panel
# LEDs: True = ON, False = OFF
print('Panel', counter, 'status:',
panel, 'at time =',
uptime(), 'seconds')
service_panel(panel)
counter += 1
# Wait 5 seconds before next read
# of the five panels.
time.sleep_ms(5000)
Since this is a simulation, the program must generate random statuses on the panels. A random number generator is used where there is a 5% random chance that a status LED will be turned ON.
Each of the five panels are polled in turn. The state of the panel's LEDs are stored in a list. After a panel read, the function any()is called on the list to determine if any of the panel's LEDs are ON (True value).
Typical Output:Starting machine monitoring... Panel 1 status: [False, False, False, True, False] at time = 10.002 seconds Panel 3 status: [True, False, False, False, False] at time = 10.008 seconds Panel 4 status: [False, False, False, False, True] at time = 25.019 seconds Panel 5 status: [False, False, True, False, False] at time = 25.025 seconds Panel 3 status: [False, False, False, False, True] at time = 30.034 seconds Traceback (most recent call last): File "main.py", line 55, in <module>> KeyboardInterrupt:Back to function list
bin()
Syntaxbin(<integer>)
Description
Converts an integer to its binary representation and returns the binary representation as a string. The string is prefixed by 0b followed by the 0's and 1's making up the binary equivalent of the integer.
For example, the integer 10 is 1010 in binary so bin(10) = '0b1010'.
The integer can be in decimal, octal or hexadecimal format. All of the following will return the binary representation '0b1010':
bin(10) decimal (base 10) bin(0o12) octal (base 8) bin(0xa) hexadecimal (base 16)
Related functions
Example 6
# Demonstrates the use and pitfalls
# of the function bin()
int1 = 5
int2 = 6
# Convert to binary representation
bin1 = bin(int1)
bin2 = bin(int2)
# 'bin1' and 'bin2' are strings.
# This is string concatenation,
# not numerical addition.
sum1 = bin1 + bin2
# 'bin1' and 'bin2' strings are converted
# to integers before the addition.
# This will give numeric addition.
sum2 = bin(int(bin1) + int(bin2))
print('WRONG... This is string concatenation')
print(bin1, '+', bin2, '=', sum1)
print()
print('CORRECT... This is numerical addition')
print(bin1, '+', bin2, '=', sum2)
print(sum2, 'in decimal form is', int(sum2))
Output:
WRONG... This is string concatenation 0b101 + 0b110 = 0b1010b110 CORRECT... This is numerical addition 0b101 + 0b110 = 0b1011 0b1011 in decimal form is 11
The result from applying the function bin() is a string. A binary value (of type string) can be converted back to an integer using the int() function. Mathematical operations can only performed when the binary representation has been converted to an integer.
The primary purpose of the bin() function is for presentation or formatted output.
Back to function listbool()
Syntaxbool(<argument>)
Description
Takes a specified argument and returns its boolean value. The bool() function returns:
- False - if argument is empty, False, 0 or None
- True - if argument is any number (besides 0), True, or any non-empty string / list / tuple / set / dictionary
# Demonstrates the use of the function bool()
# Returns False
print('bool() =', bool())
print('bool(False) =', bool(False))
print('bool(0) =', bool(0))
print('bool(None) =', bool(None))
print()
#Returns True
print('bool(3.14) =', bool(3.14))
print('bool(True) =', bool(True))
print('bool("Spam") =', bool("Spam"))
Output:
bool() = False bool(False) = False bool(0) = False bool(None) = False bool(3.14) = True bool(True) = True bool("Spam") = TrueExample 8
# Demonstrates the use of a
# user defined function that
# has a boolean return type generated
# with the built-in function bool()
# For each element of a list:
# (1) Determine if it is an integer
# (2) If an integer; is it odd or even?
# Function returns true if num is even,
# otherwise False.
# It is expected that num is an integer.
def is_even(num):
return not(bool(num % 2))
list1 = [-5, 24, 'Spam', 3 + 5j, 24.8]
print()
for item in list1:
if (type(item) == int):
# list element is an integer
if (is_even(item)):
print(item, ' is an even integer')
else:
print(item, ' is an odd integer')
else:
print(item, ' is not an integer')
Output:
-5 is an odd integer 24 is an even integer Spam is not an integer (3+5j) is not an integer 24.8 is not an integer
The function is_even() accepts an integer as its parameter. The number is divided by 2 and if the remainder is zero (0) then True is returned else False.
This relies on bool(0) returning False, i.e when there is no remainder after dividing by 2. The False value is converted to True by the not operator, signifying that the integer is even.
Back to function listbytearray()
Syntaxbytearray([<source>], [<'utf-8'>])
Note: MicroPython's syntax is a simplified form of the full Python bytearray() syntax. A full coverage of the bytearray data type can be found here
Description
Returns a bytearray object which is an array of 8-bit bytes. The bytearray class is a mutable sequence of integers in the range of 0 to 255.
The bytearray object provides some very memory efficient ways to manipulate large strings. In the case where [<source>] is of type string, utf-8 encoding can be optionally specified by adding 'utf-8' as the second argument though this has no practical effect in MicroPython.
Related functions
Example 9
# Demonstrate memory allocation of a bytearray
b1 = bytearray("Spam")
print('(1) : ', b1, '-', id(b1))
# Add a string to the end of a bytearray
b1.extend(" Cans")
print('(2) : ', b1, '-', id(b1))
# Changing single characters in a bytearray
b1[2], b1[3] = ord('u'), ord('n')
print('(3) : ', b1, '-', id(b1))
Output:
(1) : bytearray(b'Spam') - 536891008 (2) : bytearray(b'Spam Cans') - 536891008 (3) : bytearray(b'Spun Cans') - 536891008
The bytearray and the immutable equivalent bytes classes are often used as read/write buffers by microcontrollers when communicating with other devices such as sensors. They are also used by the methods of the ustruct module.
Back to function list
bytes()
MicroPython's syntax is a simplified form of the full Python bytes() syntax. A full coverage of the MicroPython (for the micro:bit) bytes data type can be found here
Syntaxbytes([<source>], [<encoding>])
Note: MicroPython enforces the use of <encoding> when <source> is a string, as per the Python language standard.
However in the case of bytearray(), MicroPython does not enforce an encoding type for a string source. It is optional which is at variance with the Python language standard.
Description
Returns an immutable bytes object initialized with the given size and data. In the case where [<source>] is of type string, an encoding type must be specified as the second argument. MicroPython accepts 'utf-8' and 'ascii'.
The parameter <source> can have the following types:
- bytes()
- Empty bytearray
- bytes(<integer>)
- bytes object containing <integer> number of members of value zero (null)
- bytes(<string>, <encoding>)
- Encoding type can be 'ascii' or 'utf-8' but must be specified.
- bytes([int_1, int_2, ...int_n])
- bytes object populated from an iterable which must contain only integers in the range 0..255. Integers outside this range will raise a ValueError exception.
Related functions
Example 10
# Demonstrate some simple uses
# of the bytes object.
# Empty bytes object
b = bytes()
print('Empty bytes object:')
print(b, '\n')
# A bytes object with 5 members
# all set to 0 (null).
b = bytes(5)
print('bytes object with 5 null elements:')
print(b, '\n')
# bytes object populated with contents
# of an iterable (list).
b = bytes([1, 2, int(31/5)])
print('bytes object from a list of integers:')
print(b, '\n')
# bytes object populated with contents
# of an iterable (set)
b = bytes((1, 2, int(31/5)))
print('bytes object from a set of integers:')
print(b, '\n')
# Example of a string converted to
# bytes object with utf-8 encoding
b1 = bytes('Spam','utf-8')
print('bytes object from string (utf-8)')
print('Elements of the bytes object:')
# Print each element of the bytes object
for i in b1:
print(i, end=" ")
print()
Output:
Empty bytes object: b'' bytes object with 5 null elements: b'\x00\x00\x00\x00\x00' bytes object from a list of integers: b'\x01\x02\x06' bytes object from a set of integers: b'\x01\x02\x06' bytes object from string (utf-8 encoding) Elements of the bytes object: 83 112 97 109
While there are inconsistencies in the way bytearray() and bytes() are implemented in MicroPython (for the micro:bit) they are never the less very useful for certain microcontroller tasks.
They are often used as the data type of choice for data buffers during communications between the microcontroller and other devices such as sensors. They are also used by the methods of the ustruct module.
Back to function listcallable()
Syntaxcallable(<object>)
Description
Returns True if the object passed appears callable. If not, it returns False. Care must be taken with this function as it may return True for a given object but in some contexts actually calling the object may raise an exception.
Example 11
# Demonstrates the use of the
# function callable().
def print_this(to_print = 'Hello World'):
print(to_print)
return('Success!')
# Is the function 'print_this' callable?
print('Is "print_this()" callable?:', end=' ')
print(callable(print_this))
# Is an integer callable?
print('Is 64 callable?:', end=' ')
print(callable(64))
Output:
Is "print_this()" callable?: True Is 64 callable?: False
In the example above the user defined function my_print_job() is callable. However the integer 64 is not callable for obvious reasons. The function call 64() is not valid and makes no sense.
Back to function listchr()
Syntaxchr(number) Parameter: number: an integer number in the range 0 to 255. Examples: chr(65) ⇒ 'A' chr(52) ⇒ ''4'' chr(400) ⇒ ValueError: chr() arg not in range(256)
Description
Converts an integer to its ascii character and returns it. MicroPython only supports a range of 0..255; anything beyond this range raises a ValueError exception.
Function ord() is the opposite to chr(). For example: chr(65) = 'A' and ord('A') = 65.
Related functions
# Demonstrates the use of the
# functions chr() and ord()
# Program prints the alphabet in
# both lowercase and uppercase.
# Prints the alphabet
def chr_print(start, finish):
count = 0
for ch in range(start, finish+1):
print(chr(ch), end=' ')
count += 1
# Print 13 characters per line
if (count % 13 == 0):
print()
print()
# Define lowercase alphabet
a = ord('a')
z = ord('z')
# Define uppercase alphabet
A = ord('A')
Z = ord('Z')
chr_print(A, Z) # print uppercase letters
chr_print(a, z) # print lowercase letters
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y zBack to function list
classmethod()
Syntaxclassmethod(function)
Description
Returns a class method for the given function. A short tutorial on MicroPython class methods with examples and usages can be found here. This function converts an instance method to a class method. Class methods are methods that are called on the class itself, not on a specific object instance.
The classmethod() function, while not depreciated from Python, is considered ‘old-fashioned’. The recommended way of specifying a class method is with the @classmethod decorator.
Related functions
Back to function listcomplex()
Syntaxcomplex(<real>[, <imaginary>]) Where: <real> A number representing the real part of the complex number. The default is 0. <imaginary> Optional. A number representing the imaginary part of the complex number. The default is 0. Examples: complex(3, 5) ⇒ (3+5j) complex(3) ⇒ complex() ⇒ 0j complex(-4.18, 5.23) ⇒ (-4.18+5.23j) complex('3+5j') ⇒ Ok for Python, MicroPython raises ValueError exception
Description
The complex() function returns a complex number by specifying a real number and an imaginary number.
Back to function listdelattr()
Syntaxdelattr(class, attribute) Parameters: class: Name of the class. attribute: String containing name of attribute to be deleted.
Description
If the class allows it, delattr() deletes the attribute from the class. Any object that has been or will be instantiated from this class will no longer have access to the deleted attribute.
Related functions
getattr(), hasattr(), setattr()
Example 13
# Demonstrates the delattr() function.
class book():
def __init__(self, title, author, pubdate):
self.title = title
self.author = author
self.pubdate = pubdate
def PrintBook(self):
print('Title is', self.title)
print('Author is', self.author)
print('Publish date is',
self.pubdate, '\n')
# Create a book and print its details.
mybook = book('MicroPython',
'Fred Cave',
'Feb-2023')
print('mybook:')
mybook.PrintBook()
# Create another book and print its details.
herbook = book('Quilting 101',
'Jane Smith',
'1905')
print('herbook:')
herbook.PrintBook()
# This will delete the method PrintBook()
# from all objects created from class book().
delattr(book, 'PrintBook')
# Attempt to print book details
try:
mybook.PrintBook()
except AttributeError as error:
print('mybook:')
print(error)
try:
herbook.PrintBook()
except AttributeError as error:
print('herbook:')
print(error)
# The method PrintBook() is deleted
# even for new book() instances.
hisbook = book('Dingo Man',
'James Dipple',
'?')
try:
hisbook.PrintBook()
except AttributeError as error:
print('hisbook:')
print(error)
Output:
mybook: Title is MicroPython Author is Fred Cave Publish date is Feb-2023 herbook: Title is Quilting 101 Author is Jane Smith Publish date is 1905 mybook: 'book' object has no attribute 'PrintBook' herbook: 'book' object has no attribute 'PrintBook' hisbook: 'book' object has no attribute 'PrintBook'Back to function list
dict()
Syntaxdict([keyword arguments]) Parameter: keyword argument consists of the following construct: key = value Examples: dict(age = 36) dict(country = "New Zealand") dict(one = 1, two = 2)
Description
The dict() function is a constructor that creates a dictionary. The [keyword arguments] are optional. There can be none, one or more of these separated by commas.
Related functions
Example 14
# Demonstrates the dict() built-in function.
# Dictionary with no entries
d1 = dict()
print("Dictionary with no entries:")
print(d1, '\n')
# Dictionary with entries
d2 = dict(name = "Jack", age = 40, job = "plumber")
print("Dictionary with entries:")
print(d2, '\n')
# Alternative to dict()
d3 = {'colour':'red', 'size':'big'}
print("Dictionary d3:")
print(d3)
Output:
Dictionary with no entries: {} Dictionary with entries: {'job': 'plumber', 'name': 'Jack', 'age': 40} Dictionary d3: {'size': 'big', 'colour': 'red'}Back to function list
dir()
Syntaxdir([<object>]) Parameter: <object> is optional and is the name of the object whose attributes are to be displayed.
Description
The dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all objects.
If no argument is passed, it returns the list of object names in the current local scope.
Related functions
Example 15
# Demonstrates the dir() built-in function.
# string object
S1 = 'Spam'
# Dictionary object
D1 = dict(name = "Jack", age = 40, job = "plumber")
# List object
L1 = [0, 1, 2, 3]
# Get directory listing of all objects
# in this program.
print('All objects:', dir(), '\n')
# Get properties and methods of
# the S1 string object and print
# them out three to a line.
print ('Properties and methods of string S1:')
count = 0
for value in dir(S1):
print(value, ' ', end='')
count += 1
if count == 3:
count = 0
print()
print('\n')
Output:
All objects: ['D1', 'L1', '__name__', 'S1'] Properties and methods of string S1: __class__ count endswith find format index isalpha isdigit islower isspace isupper join lower lstrip replace rfind rindex rsplit rstrip split startswith strip upper decode encodeBack to function list
divmod()
Syntaxdivmod(<argument1>, <argument2>) Arguments: <argument1> is divided by <argument2> Examples: divmod(11, 3) ⇒ (3, 2) divmod(-11, 3) ⇒ (-4, 1) (equivalent to 3 * -4 + 1 = -11) divmod(11.4, 3.9) ⇒ (2.0, 3.599999)
Description
The divmod() function returns a tuple containing the quotient and the remainder when <argument1> (dividend) is divided by <argument2> (divisor).
Thus this function (for integers) calculates both x // y and x % y and returns both the values. The function also works fine with float values (see example above).
Example 16
# Demonstrates the built-in function divmod()
x = divmod(11, 3)
print('divmod(11, 3) =', x)
print('11 =', x[0],'* 3 +', x[1], '\n')
y = divmod(-11, 3)
print('divmod(-11, 3) =', y)
print('-11 =', y[0],'* 3 +', y[1], '\n')
z = divmod(11.4, 3.9)
print('divmod(11.4, 3.9) =', z)
print('11.4 =', z[0],'* 3.9 +', z[1])
Output:
divmod(11, 3) = (3, 2) 11 = 3 * 3 + 2 divmod(-11, 3) = (-4, 1) -11 = -4 * 3 + 1 divmod(11.4, 3.9) = (2.0, 3.599999) 11.4 = 2.0 * 3.9 + 3.599999Back to function list
enumerate()
Syntaxenumerate(<iterable>, [<start>]) Parameters: <iterable> - sequence, an iterator, or object that support iteration. <start> - (optional) starts counting from this number. Default is 0. Example: E = enumerate(['boy', 'girl'], 50) D = dict(E) D ⇒ {50: 'boy', 51: 'girl'} D[50] ⇒ 'boy' D[51] ⇒ 'girl'
Description
The enumerate() function adds a counter to an iterable[2] and returns it. The returned object is an enumerate object.
The enumerate object is returned in a key-value pair format. The key is the corresponding index of each item and the value is the items.
The enumerate object can be converted to a list, tuple or dictionary using the list(), tuple() and dict() functions respectively.
The enunerate() function can be very useful in for loops. See Example 17 below.
Related functions
Example 17
# Demonstrates the built-in function enumerate()
Colours = ['red', 'green', 'blue']
Clothes = 'pants', 'shirt', 'skirt'
Fruits = ('orange', 'mango', 'peach')
eColours = enumerate(Colours)
print('List -> ')
print(list(eColours), '\n')
eClothes = enumerate(Clothes, 100)
print('Tuple -> ')
print(tuple(eClothes), '\n')
print("'for' loop example:")
for counter, fruit in enumerate(Fruits, 1):
print(counter, fruit)
Output:
List -> [(0, 'red'), (1, 'green'), (2, 'blue')] Tuple -> ((100, 'pants'), (101, 'shirt'), (102, 'skirt')) 'for' loop example: 1 orange 2 mango 3 peachBack to function list
eval()
Syntaxeval(<expression>[, globals[, locals]]) Parameters: <expression>: String is parsed and evaluated as a Python expression. globals [optional]: Dictionary to specify the available global methods and variables. locals [optional]: Dictionary to specify the available local methods and variables. Examples: eval('5 * 8') ⇒ 40 pi = 3.14159 r = 2 eval('pi * pow(r, 2)') ⇒ 12.56636 eval('x = 2') Assignment statement, not an expression. This will give the following error. ⇒ Traceback (most recent call last): File "<stdin>", line 1, in <module>> File "<string>", line 1 SyntaxError: invalid syntax Global dictionary example eval('sum(x)', {'x' : [2, 3, 4]}) ⇒ 9
Description
The eval() function evaluates the specified expression and if the expression is a legal MicroPython statement, it will be executed. This allows MicroPython expressions to be dynamically built and executed in a program.
The first parameter passed to eval() must be an expression. It cannot be a compound statement e.g. a for loop or an assignment statement.
Related functions
Back to function listexec()
Syntaxexec(<object>[, globals[, locals]]) Parameters: <object>: String object containing code to be executed. globals: Optional dictionary containing global parameters. locals: Optional dictionary containing local parameters.
Description
The exec() function is used to execute the specified Python code. MicroPython requires the code to be executed to be a string.
While eval() can only evaluate a MicroPython expression e.g. eval('4 + 5'), exec() will execute full blocks of code.
The parameters globals and locals will not be discussed further in this posting. These are optional and might not be used often with embedded MicroPython programs in a microcontroller.
Related functions
Example 18
# Demonstrates the exec() built-in function.
# This program will dynamically construct the following
# MicroPython code then execute it as a program.
################################
# List = [34, 86, 1, 256, 63]
# for item in List:
# if (item % 2) == 0:
# print(item, 'is even')
# else:
# print(item, 'is odd')
###############################
# Build the dynamic code
myCode = 'List = [34, 86, 1, 256, 63]\n'
myCode += 'for item in List:\n'
myCode += ' if (item % 2) == 0:\n'
myCode += ' print(item, "is even")\n'
myCode += ' else:\n'
myCode += ' print(item, "is odd")\n'
# Execute the dynamic code
print('Program code to execute:')
print(myCode)
print('Output:')
exec(myCode)
Output:
Program code to execute: List = [34, 86, 1, 256, 63] for item in List: if (item % 2) == 0: print(item, "is even") else: print(item, "is odd") Output: 34 is even 86 is even 1 is odd 256 is even 63 is oddBack to function list
filter()
Syntaxfilter(function, iterable) Parameters: function: Function to be run for each item in the iterable. iterable: Iterable (eg list, tuple, dictionary) to be filtered. Returns: An iterator of filtered elements.
Description
The filter() function returns an iterator where the items are filtered through a function to test if the item is accepted or not. Sounds complicated, but it isn't really. It's easily understood through an example - see Example 19 below.
Related functions
Example 19
# Demonstrates the built-in filter() function.
# Dictionary of all agents
agent1 = {'Name':'Fred', 'Age':35}
agent2 = {'Name':'Jack', 'Age':70}
agent3 = {'Name':'Bill', 'Age':43}
agentList = [agent1, agent2, agent3]
# Agent mandatory retirement age
OLD = 65
def notRetired(agent):
# An agent is retired if they
# have reached the mandatory
# retirement age.
if agent['Age'] < OLD:
return True
else:
return False
# Filter out all agents who are retired.
active = filter(notRetired, agentList)
for those in active:
print(those)
Output:
{'Name': 'Fred', 'Age': 35} {'Name': 'Bill', 'Age': 43}
Note that the filter() function returns an iterator not a list. That is why the for loop is needed in the example above to produce the output showing the active agents.
Back to function listfloat()
Syntaxfloat(value) Parameters: value: A number or a string that can be converted into a floating point number. Examples float(5) ⇒ 5.0 float(-5) ⇒ -5.0 float(3 ** 5) ⇒ 243.0 float(6.89) ⇒ 6.89 float('98') ⇒ 98.0 float(4 + 3j) ⇒ TypeError: can't convert complex to float float([54]) ⇒ TypeError: can't convert list to float
Description
The float() function converts the specified value into a floating point number.
Related functions
Back to function listgetattr()
Syntaxgetattr(object, attribute[, default]) Parameters: object: Object whose named attribute's value is to be returned. attribute: String that contains the attribute's name. default: Optional value returned when the attribute is not found.
Description
The getattr() function returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.
Related functions
delattr(), hasattr(), setattr()
Example 20
# Demonstrates the built-in getttr() function.
class SecretAgents:
agent1 = {'Name':'Fred', 'Age':35}
agent2 = {'Name':'Jack', 'Age':70}
agent3 = {'Name':'Bill', 'Age':43}
agency = 'CIA'
# Create an instance of the SecretAgents class
myAgents = SecretAgents()
# Get details of some secret agents
print('The agency is')
print(getattr(myAgents, 'agency'), '\n')
print('The age of agent1 is')
print(getattr(myAgents, 'agent1')['Age'], '\n')
print('Agent4 details:')
print(getattr(myAgents,
'agent4',
'No such agent'))
Output:
The agency is CIA The age of agent1 is 35 Agent4 details: No such agentBack to function list
globals()
Syntaxglobals()
Description
The globals() function returns the dictionary of the current global symbol table.
Related functions
Example 21
# Demonstrate built-in globals() function.
# Demonstrate built-in locals() function.
class SecretAgents:
agent1 = {'Name':'Fred', 'Age':35}
agent2 = {'Name':'Jack', 'Age':70}
agent3 = {'Name':'Bill', 'Age':43}
agency = 'CIA'
print('SecretAgents local dictionary:')
for l in locals():
print(l)
myAgents = SecretAgents()
print()
print('Global dictionary:')
for g in globals():
print(g)
Output:
SecretAgents local dictionary keys: agent2 l agency __qualname__ agent1 agent2 agent3 Global dictionary keys: SecretAgents __name__ myAgentsBack to function list
hasattr()
Syntaxhasattr(object, attribute) Parameters: object: Name of the object. attribute: String containing name of the attribute.
Description
The function hasattr() returns True if the specified object has the specified attribute else it returns False.
Related functions
delattr(), getattr(), setattr()
Example 22
# Demonstrate the built-in hasattr() function.
class SecretAgents:
agent1 = {'Name':'Fred', 'Age':35}
agent2 = {'Name':'Jack', 'Age':70}
agent3 = {'Name':'Bill', 'Age':43}
agency = 'CIA'
myAgents = SecretAgents()
if hasattr(myAgents, 'agent1'):
print('agent1 details:', myAgents.agent1)
else:
print('agent1 not found')
if hasattr(myAgents, 'agent4'):
print('agent4 details:', myAgents.agent1)
else:
print('agent4 not found')
Output
agent1 details: {'Name': 'Fred', 'Age': 35} agent4 not foundBack to function list
hash()
Syntaxhash(object) Parameter: object: The object whose hash value is to be returned. Examples: hash(52) ⇒ 52 hash('Spam') ⇒ 51882 hash((1, 2, 3)) ⇒ 362898 A list is a mutable type object. This will give an error. hash([1, 2, 3]) ⇒ TypeError: unsupported type for __hash__: 'list'
Description
The hash() function returns the hash value of an object if it has one. Hash values are computed integers used internally by MicroPython to compare dictionary keys during a quick dictionary look up.
It returns hashed value only for immutable objects, hence can be used as an indicator to check for mutable/immutable objects.
Back to function listhelp()
Syntaxdir([object]) Parameter: object: Optional and is the name of the object whose documentation is to be displayed.
Description
The MicroPython help() function is used to get the documentation of the specified module, class, function, variables etc. This method does not work as expected with MicroPython on the micro:bit. It appears to have very limited usefulness.
Typing help() into the REPL on the Mu Editor produces the following output:
>>> help() Welcome to MicroPython on the micro:bit!
Typing help('modules') into the REPL on the Mu Editor produces the following output:
__main__ machine os uerrno antigravity math radio urandom audio microbit speech ustruct builtins micropython this usys gc music uarray utime love neopixel ucollections Plus any modules on the filesystem
Related functions
Back to function listhex()
Syntaxhex(integer)
Description
Converts an integer number to its hexadecimal (base 16) representation and returns the hexadecimal representation in a string format. The string is prefixed by '0x' followed by the 0's to 9's and 'a's to 'f's making up the hexadecimal equivalent of the integer. For example, the integer 100 is 64 in hexadecimal so hex(10) = '0x64'.
The integer can be in decimal, octal or binary format. All of the following will return the hexadecimal representation '0xa':
hex(10) hexadecimal value hex(0o12) octal value hex(0b1010) binary value
Related functions
Example 23
# Demonstrates the built-in function hex()
int1 = 25
int2 = 26
hex1 = hex(int1)
hex2 = hex(int2)
# String concatenation,
# not numerical addition
sum1 = hex1 + hex2
print('WRONG...')
print(hex1, '+', hex2, '=', sum1, '\n')
# Correct numerical addition
sum2 = hex(int(hex1) + int(hex2))
print('CORRECT...')
print(hex1, '+', hex2, '=', sum2, '\n')
print('Converting to decimal...')
print(sum2, '=', int(sum2))
Output:
WRONG... 0x19 + 0x1a = 0x190x1a CORRECT... 0x19 + 0x1a = 0x33 Converting to decimal... 0x33 = 51
The result of the function hex() is a string. A hexadecimal represented string can be converted back to an integer using the int() function. Mathematical operations can only performed when the hexadecimal representation has been converted to the equivalent integer.
The primary purpose of the hex() function is for presentation or formatted output.
Back to function listid()
Syntaxid(object) Parameter: object: Any MicroPython object e.g. list, tuple, set, string, number Example: id(5) ⇒ 11 id({1, 2, 3}) ⇒ 536891920 id('Spam') ⇒ 6858
Description
The id() function returns the “identity” of the object. The identity of an object is an integer, which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id value.
Back to function listinput()
Syntaxinput(prompt) Parameter: prompt: A string, representing a default message before the input.
Description
The input() function allows user input. Though MicroPython does provide this function it has limited use for the programming of microcontrollers. If it is used in a normal MicroPython program that is flashed to the micro:bit there is no way for the user to see the prompt and enter an input via the keyboard. However the function will work as intended if entered into the REPL.
Example 24Copy the following code and paste it directly into the REPL on the Mu Editor. Press the enter key.
name = input('What is your name? ')
print('Your name is', name)
Output:
What is your name? Fred Cave Your name is Fred CaveBack to function list
int()
Syntaxint(value[, base]) Parameters: value: A number or a string that can be converted into a base 10 integer. base: Optional, the base of value. The default is base 10. If not base 10 then value must be a string.> Examples int(5.8) ⇒ 5 int(-5.8) ⇒ -5 int(3.2 ** 5.6) ⇒ 674 int(689) ⇒ 689 int('98') ⇒ 98 int('98.9') ⇒ ValueError: invalid syntax for integer with base 10 int(4 + 3j) ⇒ TypeError: can't convert complex to int int([54]) ⇒ TypeError: can't convert list to int Convert a base 5 value to base 10: int('24', 5) ⇒ 14
Description
The int() function:
- Returns an integer from a number or string
- Converts a number in a given base to a base 10 integer.
Related functions
Back to function listisinstance()
Syntax
isinstance(object, type)
Parameters:
object: Any MicroPython object to have
its type tested.
type: One or more types.
Example:
isinstance(45, (int, float)) ⇒ True
Description
The isinstance() function returns True if the specified object is of the specified type, otherwise False.
If more than one type is passed to the function the types are parcelled as a tuple e.g. (set, list, dictionary)
Related functions
Example 25
# Demonstrates built-in function isinstance()
# A list is traversed and for all elements
# that are numbers the square root is
# calculated and output.
# Any negative number is converted
# to a positive value.
# An error message is output for any element
# that isn't a number.
from math import sqrt, pi
List = [23, pi,'Spam', -52.657]
for item in List:
if isinstance(item, (int, float)):
# Numerical, so make sure
# it is positive then calculate
# the square root.
item = abs(item)
print('Square root of',
item, 'is:', sqrt(item))
else:
# Not numerical
# so print an error message.
print(item, 'is not a number')
Output:
Square root of 23 is: 4.795832 Square root of 3.141593 is: 1.772454 Spam is not a number Square root of 52.657 is: 7.256515Back to function list
issubclass()
Syntaxissubclass(object, subclass) Parameters: object: A MicroPython object subclass: A class object, or a tuple of class objects.
Description
The issubclass() function returns True if the object (first parameter) is a subclass of the specified class (second parameter), otherwise False.
More than one object can be tested for subclass membership in a single call to the function. In this case the class objects are passed as a tuple.
Example 26
# Demonstrate the built-in function issubclass()
# The program defines four classes.
# The first three classes have close
# inherentence links.
# The fourth class, Dealership(), is
# totally unrelated to the other three classes.
# Base class
class Car:
doors = 2
wheels = 4
#Child class of Car
class Rover(Car):
def service(self):
pas # Do something!
# Child class of Rover
class MoonRover(Rover):
pass # Do something!
# Class unrelated to Car, Rover or MoonRover
class Dealership():
pass # Do something!
print('Rover is a subclass of Car:',
issubclass(Rover, Car))
print('MoonRover is a subclass of Car:',
issubclass(MoonRover, Car))
print('MoonRover is a subclass of Rover:',
issubclass(MoonRover, Rover))
print('Dealership is a subclass of Car:',
issubclass(Dealership, Car))
Output:
Rover is a subclass of Car: True MoonRover is a subclass of Car: True MoonRover is a subclass of Rover: True Dealership is a subclass of Car: FalseBack to function list
iter()
Syntaxiter(object[, sentinel]) Parameter: object: An iterable object e.g. string, list, tuple, set, dictionary.
Description
The iter() function returns an iterator for the given argument.
Related functions
# Demonstrate built-in functions iter() and next()
Set = {1, 2, 3, 4, 5}
# This is the conventional way to output an iterable.
for item in Set:
print(item, end=' ')
print('\n')
# To execute the above, MicroPython converts
# the set to an iterator with iter() then
# traverses each element of set by using
# next() on the iterator.
iterSet = iter(Set)
for item in range(0, len(Set)):
print(next(iterSet), end=' ')
print()
5 1 2 3 4 5 1 2 3 4Back to function list
len()
Syntaxlen(object) Paameter: object: Any object that is a sequence or a collection. Examples: len('Spam') ⇒ 4 len({'orange', 'lemon', 'apple'}) ⇒ 3 len({'wheels':4, 'doors':2}) ⇒ 2 len(5) ⇒ TypeError: object of type 'int' has no len()
Description
The len() function returns the number of items in an object. For example, when the object is a string, the function returns the number of characters in the string. This an incredibly useful function.
Back to function listlist()
Syntaxlist([iterable]) Parameter: itearble: Optional, a sequence, collection or an iterator object. Examples: # Convert a string to a list list('Spam') ⇒ ['S', 'p', 'a', 'm'] # Converting a dictionary to a list creates a list of the dictionary keys list({'colour':'red', 'type':'sedan'}) ⇒ ['type', 'colour'] Empty list list() ⇒ []
Description
The list() function creates a list object. If a parameter is provided MicroPython will attempt to convert it to a list. If no parameter is given then an empty list is returned.
Related functions
# Demonstrate built-in functions list() and set()
# This program will demonstrate a technique
# for removing duplicate values from a list.
# First step is to convert the
# list object to a set object.
# By definition a set is unordered
# and has no duplicates.
# When the list is converted to a set
# any duplicates will be dropped.
# Finally, the set object is converted
# back to a list object.
L = ['one', 1, 'L', 'one', 5.26, 1]
count = len(L)
print('Original list:', L)
# Convert to a set, all duplicates are dropped.
S = set(L)
# Convert back to a list, with no duplicates.
L = list(S)
print('List with duplicates removed:', L)
print('Number of duplicates removed:', count - len(L))
Original list: ['one', 1, 'L', 'one', 5.26, 1] List with duplicates removed: [5.26, 1, 'one', 'L'] Number of duplicates removed: 2
Back to function list
locals()
Syntaxlocals()
Description
The locals() function returns the dictionary of the current local symbol table at the point in the program where the function is called.
Related functions
Back to function listmap()
Syntaxmap(function, iterables) Parameters: function: The function to execute on each iterable. iterables: One or more sequence, collection or iterator objects.The function must have one parameter for each iterable. Returns: An iterator object.
Description
The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.
Related functions
Example 29
# Demonstrates built-in function map().
# Square root function.
from math import sqrt
# EXAMPLE 1
# Calculates and outputs the square root
# of all elements of a set.
Set = (23, 45, 9, 5.42)
print('EXAMPLE 1')
print('The set is:', Set)
# Use map() to calculate the square root
# of all elements of the set and store
# in another set.
sqrtSet = map(sqrt, Set)
print('The square roots are:', end=' ')
for item in sqrtSet: print(item, end=' ')
# EXAMPLE 2
# Calculates and outputs the sums of
# equivalent elements of three lists.
List1 = [23, 45, 90]
List2 = [32, 89, 2, 5]
List3 = [65, 86, 32]
print('\n\nEXAMPLE 2')
print(List1, List2, List3)
def Sum(x, y, z):
return x + y + z
# First time round List1[0], List2[0] and List3[0]
# are summed and printed out.
# Then List1[1], List2[1] and List3[1]
# are summed and printed out.
# This continues till all elements have been
# iterarted through, summed and printed.
sumList = map(Sum, List1, List2, List3)
print('The sums are:', end=' ')
for item in sumList: print(item, end=' ')
print()
def Sum(x, y, z):
return x + y + z
sumList = map(Sum, List1, List2, List3)
print('The sums are:')
for item in sumList:
print(item)
Output:
EXAMPLE 1 The set is: (23, 45, 9, 5.42) The square roots are: 4.795832 6.708204 3.0 2.328089 EXAMPLE 2 [23, 45, 90] [32, 89, 2, 5] [65, 86, 32] The sums are: 120 220 124
Each use of map() in the example above returns an iterator. A for loop is used to access each element of the iterator to output the value.
Back to function listmax()
SyntaxForm 1: max(n1, n2[, n3, ...]) Form 2: max(iterable) Parameters: n1, n2[], n3, ...] Two or more items to compare. iterable: An iterable, with one or more items to compare. Examples: max(23.1, 6, 53) ⇒ 53 max('23.1', '6', '53') ⇒ '6' max([8, 78, 99, pow(9, 3)]) ⇒ 729 max({'wheels':4, 'doors':'2'}) ⇒ 'wheels'
Description
The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetical comparison is done.
Related functions
Back to function listmemoryview()
Syntaxmemoryview(obj) Parameter: obj: object whose internal data is to be exposed.
Description
The memoryview() function returns memoryview[3] objects. A memoryview object allows MicroPython code to access the internal data of an object that supports the buffer protocol without copying.
Objects that support the buffer protocol include bytearrays[3], bytes[3], string and uarray.array[3]. A bytearray may, for example, contain a very large block of text. Each time this bytearray is passed to a function (both built-in and user coded) a copy must be created. It is this copy that the function operates upon.
Instead if a memoryview object is passed to the function there is no copying necessary and the function operates directly on the object's data. This is similiar to passing arguments by reference in other languages such as C++. This can result in large processing efficiencies.
Example 30
# Demonstrate built-in function memoryview()
# Function to print the elements of
# an iterable object.
def output(obj,name):
print('elements of', name, ': ', end=' ')
for elements in obj:
print(elements, end=' ')
print()
# Define a bytearray object then
# obtain a memoryview object of it.
print('Initial objects')
B = bytearray([0,1,2,3,4,5,6,7,8,9])
output(B, 'bytearray')
M = memoryview(B)
output(M, 'memoryview')
# Change first element in the memoryview (M)
M[0] = 9
# Change second element in the bytearray (B)
B[1] = 8
# Output the two objects again.
# The first two elements of the bytearray
# and memoryview will be changed in an
# identical fashion. This indicates that
# the memoryobject M does indeed reference the
# same physical memory of the bytearray B.
print('\nFinal objects')
output(B, 'bytearray')
output(M, 'memoryview')
Output:
Initial objects elements of bytearray : 0 1 2 3 4 5 6 7 8 9 elements of memoryview : 0 1 2 3 4 5 6 7 8 9 Final objects elements of bytearray : 9 8 2 3 4 5 6 7 8 9 elements of memoryview : 9 8 2 3 4 5 6 7 8 9Back to function list
min()
SyntaxForm 1: min(n1, n2[, n3, ...]) Form 2: min(iterable) Parameters: n1, n2[, n3, ...] Two or more items to compare. iterable: An iterable, with one or more items to compare. Examples: min(23.1, 6, 53) ⇒ 6 min('23.1', '6', '53') ⇒ '23.1' min([8, 78, 99, pow(9, 3)]) ⇒ 8 min({'wheels':4, 'doors':'2'}) ⇒ 'doors'
Description
The min() function returns the item with the lowest value, or the item with the lowest value in an iterable. If the values are strings, an alphabetical comparison is done.
Related functions
Back to function listnext()
Syntaxnext(iterable) Parameter: iterable: Any iterable object e.g. set, list, string, dictionary.
Description
The next() function returns the next item in an iterator.
Related functions
ExampleAn example of this function can be found here where the iter() function is discussed.
Back to function listobject()
Syntaxobject() Parameters: This function has no parameters. Example: obj = object()
Description
The object() function returns a featureless object which is a base for all classes.
Back to function listoct()
Syntaxoct(integer) Parameter: integer: Any integer
Description
The oct() function converts an integer number to its octal (base 8) representation and returns the octal representation in a string format. The string is prefixed by 0o followed by the 0's to 7's making up the octal equivalent of the integer. For example, the integer 10 is 12 in octal so oct(10) = '0o12'.
The integer can be in decimal, binary or hexadecimal format. All of the following will return the octal representation '0o12':
Decimal (base 10) oct(10) ⇒ '0o12' Binary oct(0b1010) ⇒ '0o12' Hexadecimal oct(0xa) ⇒ '0o12'
Related functions
Example 31
# Demonstrates the built-in function oct()
int1 = 15
int2 = 16
# Convert to octal
oct1 = oct(int1)
oct2 = oct(int2)
# String concatenation, not numerical addition.
sum1 = oct1 + oct2
print('WRONG...',
oct1, '+', oct2, '=', sum1)
# Correct numerical addition.
sum2 = oct(int(oct1) + int(oct2))
print('CORRECT...', oct1, '+', oct2, '=', sum2)
# Convert the sum to decimal.
print('Converting to decimal...', sum2, '=', int(sum2))
Output:
WRONG... 0o17 + 0o20 = 0o170o20 CORRECT... 0o17 + 0o20 = 0o37 Converting to decimal... 0o37 = 31
The result of the function oct() is a string. A octal represented string can be converted back to a decimal integer using the int() function.
Mathematical operations can only be performed when the octal representation has been converted to the equivalent decimal integer.
The primary purpose of the oct() function is for presentation or formatted output.
open()
Syntaxopen(file[, mode]) Parameters: file: The path and name of the file. mode: Optional, a string which defines mode to open the file in: 'r' - Read - Default value, opens a file for reading; error if the file does not exist. 'w' - Write - Opens a file for writing, creates the file if it does not exist. Additionnaly the file can be specified as text or binary: 't' - Default, Text mode. 'b' - Binary mode. Examples: # Opens 'speed.dat' for reading in text mode. open('speed.dat') # Opens 'dump.bin' for writing in binary mode. open('dump.bin', 'wb')
Description
The open() function opens a file, and returns it as a file object. A tutorial on file handling in MicroPython can be found here.
Back to function listord()
Syntaxord(character) Parameter: character: A single ascii character. Examples: ord('A') ⇒ 65 ord('4') ⇒ 52
Description
Returns an integer representing the Unicode character. Python's version of this function will accept any standard unicode character.
However in MicroPython the character must be a member of the original ascii set that returns a value in the range 0..255. Any other character passed will raise a TypeError exception.
Related functions
ExampleExample 12 demonstrates the use of ord() and its inverse function chr().
Back to function listpow()
Syntaxpow(base, exponent) Parameters: base: An integer, float or complex number exponent: An integer, float or complex number Examples: pow(5, 4) ⇒ 625 pow(625, 1/4) ⇒ 5.0 pow(97.612, 2.6795) ⇒ 214226.9 pow(3.14 + 4.6j, 2.3 + 9.1j) ⇒ (0.004130766-0.006250403j)
Description
The pow(x, y) function returns the value of x raised to the power of y i.e. xy.
Back to function listprint()
Syntaxprint(*objects[, sep=string, end=string]) Parameters: *objects: One or more objects separated by commas. Optional * will unpack an object with multiple elements. sep: Optional string printed as separator of multiple items on a line. Default is a space (' '). end: Optional string that will be printed at the end of the line. Default is a new line character ('\n'). Example:
Description
The print() function prints the given object to the standard output device (REPL).
Example 32
# Demonstrates built-in print() function.
# Square root function
from math import sqrt
# Simple examples
print('Simple examples')
print('Square root of 5 =', sqrt(5))
print([1, 2, 3, 4, 'Spam'])
print('\n') # Newline character
# Unpacking an object with multiple elements
print('Unpacking an object with multiple elements')
print(*[1, 2, 3, 4, 'Spam'])
print(*[1, 2, 3, 4, 'Spam'], sep=' | ')
# Specifying a line ending string
print('\nUsing a line end string')
t = 'H','e','l','l','o',' ','W','o','r','l','d'
for element in t:
print(element, end='')
print()
Output:
Simple examples Square root of 5 = 2.236068 [1, 2, 3, 4, 'Spam'] Unpacking an object with multiple elements 1 2 3 4 Spam 1 | 2 | 3 | 4 | Spam Using a line end string Hello WorldBack to function list
property()
Syntaxproperty(fget=None, fset=None, fdel=None, doc=None) Parameters:: fget: Function to return the value of the managed attribute. fset: Function to set the value of the managed attribute. fdel: Function that defines how to handle the deletion of the managed attribute. doc: Docstring available when using the help() function.
Description
With MicroPython's property(), managed attributes can be created in classes. Managed attributes, also known as properties, are useful when needing to modify the internal implementation of a class without changing its public interface.
This allows improved/additional functionality to be introduced into a class without breaking any existing usage of this class.
This is a full topic in its own right and is covered in some detail with examples here.
Back to function listrange()
Syntaxrange(start, stop, step) Parameters: start: Optional, integer specifying first number in the range. Default is 0. stop: Integer; range stops just before this number. step: Otional, integer value used as the increment. Default = 1. Examples: range(5) ⇒ 0 1 2 3 4 range(1, 5) ⇒ 1 2 3 4 range(1, 9, 2) ⇒ 1 3 5 7 range(1, 9.4, 2) TypeError: can't convert float to int range('A', 'E') ⇒ TypeError: can't convert str to int range(ord('A'), ord('E')) ⇒ 65 66 67 68
Description
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 by default, and stops before a specified number.
The range() function is especially useful in for loops.
Example 33
# Example of range() function in a for loop.
# This program sums the first 10,000 integers.
start = 1
end = 10000
# Function that sums a range
# of sequential integers.
def doSum(first, last):
sum = 0
for count in range(first, last +1):
sum +=count
return sum
print('Sum of integers from',
start,'to', end,'is',
doSum(start, end))
Output:
Sum of integers from 1 to 10000 is 50005000Back to function list
repr()
Syntaxrepr(obj) Prameter: obj: The object whose printable representation is to be returned.
Description
The repr() method returns a string containing a printable representation of an object. This function calls the underlying __repr__() function of the object.
In a user defined class, __repr__ can be overridden to provide a better output result than the default behaviour.
Example 34
# Demonstrates built-in repr() function.
class student():
firstname = 'Jack'
lastname = 'Brown'
# Class constructor
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
# Returns a formatted view of the class
# suitable for use with the print() function.
def __repr__(self):
return self.firstname + ' ' + self.lastname
myStudent = student('Chris', 'Jones')
# The repr() function calls the __repr__() method.
print('My student is', repr(myStudent))
Output:
My student is Chris JonesBack to function list
reversed()
Syntaxreversed(sequence) Parameter: sequence: Any iterable object that is subscriptable.
Description
The reversed() function returns an iterator object with the elements of a sequence, subscriptable object in reverse order. Objects that the reversed() function can operate on include string, tuple , list and range.
The function cannot be used on set and dictionary objects as these types aren't subscriptable. A set doesn't have a defined order and the values in a dictionary are defined by their keys.
Example 35
# Demonstrate built-in reversed() function.
# Output the elements of an iterable object.
def Output(obj):
for those in obj:
print(those, end=' ')
print()
# Reverse the order of a list
L = [1, 2, 3.498, 'Spam']
Output(L)
L = reversed(L)
Output(L)
# Reverse the order of a tuple.
T = (45, 'world', [1, 2, 3.498, 'Spam'])
print()
Output(T)
Output(reversed(T))
# Reverse the order of a string.
S = 'dlroW olleH'
print()
Output(S)
S = reversed(S)
Output(S)
# Attempt to reverse the order of a set
# This will result in a TypeError exception
# being raised.
Set = {1, 2, 3, 4, 5}
print()
Output(Set)
Set = reversed(Set)
Output(Set)
Output:
1 2 3.498 Spam Spam 3.498 2 1 45 world [1, 2, 3.498, 'Spam'] [1, 2, 3.498, 'Spam'] world 45 d l r o W o l l e H H e l l o W o r l d 5 1 2 3 4 Traceback (most recent call last): File "main.py", line 35, in <module> File "main.py", line 5, in Output TypeError: 'set' object isn't subscriptableBack to function list
round()
Syntaxround(number, digits) Paramters: number: The number to be rounded. digits: Optional, number is rounded to this number of decimals. Default = 0 Examples: round(5.6) ⇒ 6 round(5.4) ⇒ 5 round(5.416398, 4) ⇒ 5.4164 round(3.1412 + 5.2j) ⇒ TypeError: can't convert complex to float round('67.94', 1) ⇒ TypeError: can't convert str to float round(float('67.94'), 1) ⇒ 67.9
Description
The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals.
The default number of decimals is 0, meaning that the function will return the nearest integer.
Back to function listset()
Syntaxset([iterable]) Parameter: itearble: Optional, a sequence, collection or an iterator object. Examples: set('Spam') ⇒ {'a', 'p', 'S', 'm'} set({'colour':'red', 'type':'sedan'}) ⇒ {'colour', 'type'} set() ⇒ set()
Description
The set() function creates a set object. If a parameter is provided MicroPython will attempt to convert it to a set. If no parameter is given then an empty set is returned. As shown in the third example above, an empty set is represented by set() not {} since this is the notation for an empty dictionary.
If set() is applied to a dictionary, a set containing the dictionary keys will be returned.
Related functions
dict(), list(), str(), tuple()
ExampleSee Example 28 demonstrating the usage of set() and list()
Back to function listsetattr()
Syntaxsetattr(;object, attribute, value) Parameters: object: The object to set an attribute on. attribute: The name (as a string) of the attribute to set. value: The value to assign to the attribute.
Description
The setattr() function sets the specified value of the specified attribute of the specified object.
Related functions
delattr(), getattr(), hasattr()
Example 36
# Demonstrate setattr() and getattr() functions.
class SecretAgents:
agent1 = {'Name':'Fred', 'Age':35}
agent2 = {'Name':'Jack', 'Age':70}
agent3 = {'Name':'Bill', 'Age':43}
agency = 'CIA'
myAgents = SecretAgents()
print('The agency is', getattr(myAgents, 'agency'))
print('Updating the agency')
setattr(myAgents, 'agency', 'FBI')
print('The agency is now', myAgents.agency)
Output
The agency is CIA Updating the agency The agency now is FBIBack to function list
sorted()
Syntaxsorted(iterable[, key=key, reverse=reverse]) Parameters: iterable: The sequence to sort e.g. a list, dictionary, tuple etc. key: Optional, function to execute that provides the sort order. Default is None. reverse: Optional boolean; False will sort ascending. True will sort descending. Default is False.
Description
The sorted() function sorts the elements of a given iterable in a specific order (ascending or descending) and returns it as a list. An optional function (key) can be passed as an argument to define a custom sort order.
Example 37
# Demonstrate the buult-in function sorted().
# Sort a list of strings based on string length.
# outputs all items of an iterable object.
def Output(obj):
for those in obj:
print(those, end=' ')
print('\n')
# A list of strings
L = ['The',
'little',
'lamb',
'is',
'callest',
'"Bah Bah"']
print('Original list of strings:')
Output(L)
# Sort strings alphabetically
print('Sorted alphabetically:')
Output(sorted(L))
# Sort strings shortest to longest.
print('Sorted shortest to longest string length:')
Output(sorted(L, key = len))
# Sort strings longest to shortest.
print('Sorted longest to shortest string length:')
Output(sorted(L, key = len, reverse = True))
Output:
Original list of strings: the little lamb is callest "Bah Bah" Sorted alphabetically: "Bah Bah" callest is lamb little the Sorted from shortest to longest string length: is the lamb little callest "Bah Bah" Sorted from longest to shortest string length: "Bah Bah" callest little lamb the isBack to function list
staticmethod()
Syntaxstaticmethod(function)
Description
Returns a static method from a given instance method. A short tutorial on MicroPython static methods with examples can be found here.
From digitalocean.com:
Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class.
The staticmethod() function, while not depreciated from Python, is considered ‘old-fashioned’. The recommended way of classifying a static method is with the @staticmethod decorator.
Related functions
Back to function liststr()
Syntaxstr(object) Parameter: object: Optional, object to be converted to a string object. Examples: str(5) ⇒ '5' str(3.1415) ⇒ '3.1415' str(['S', 'p', 'a', 'm']) ⇒ "['S', 'p', 'a', 'm']" str() ⇒ ''
Description
The str() function returns the string representation of a given object. If no parameter is given, the function returns an empty string.
Related functions
dict(), list(), set(), tuple()
Back to function listsum()
Syntaxsum(iterable[, start]) Paramters: iterable: Any iterable (list, tuple, set, etc) containing only numbers; i.e. any combination of integer, float or complex. start: Optional value that is added to the sum of the items. Default = 0. Examples: sum((1, 2, 3)) ⇒ 6 sum((1.0, 2, 3), 100) ⇒ 106.0 sum([1, pow(9, 4), 3 + 4j]) ⇒ (6565+4j)
Description
The sum() function adds the items of an iterable and returns the sum.
Back to function listsuper()
Syntaxsuper() Note: This is the simplest form of the function and most commonly used.
Description
The super() function provides access to methods in a superclass from the subclass that inherits from it. Calling super() returns a temporary object of the superclass that then allows calls to the superclass's methods.
This article will only be discussing the simplest use of this powerful function, concluding with an example of single inheritance. An excellent and detailed discussion of this function including examples of multiple inheritance can be found at realpython.com.
Example 38
# Demonstrate built-in function super()
# Square root function.
from math import sqrt
class Triangle:
# The Triangle can be any three sided shape.
# a, b, c are the side lengths of the triangle.
# Class constructor
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
# Calculate area of triangle.
def area(self):
# Calculated using Heron's Formula
a, b, c = self.a, self.b, self.c
s = (a+b+c)/2
return sqrt(s * (s-a) * (s-b) * (s-c))
# Calculate perimeter of triangle.
def perimeter(self):
return self.a + self.b + self.c
class RightAngleTriangle(Triangle):
# A right angle triangle is just a
# specific type of triangle.
# The area and perimeter calulations for
# a right angle triangle can be performed by
# the methods of the Triangle class.
def __init__(self, a, b):
# The dimensions of a
# right angle triangle can be defined
# with just the two side lengths.
# The hypotenuse does not need to be provided
# as it can be easily calculated.
self.a = a
self.b = b
# Calculate the hypotenuse
hyp = sqrt(a*a + b*b)
# Need to return a Triangle object
# so that the area and hypotenuse of the
# right angle triangle can be calculated.
super().__init__(a, b, hyp)
# Define triangle of any shape
Scalene = Triangle(5.342,10.4,12.9)
print('Scalene triangle')
print('Dimensions:',Scalene.a, ',',
Scalene.b, ',', Scalene.c)
print('Perimeter =',Scalene.perimeter())
print('Area =',Scalene.area())
# Define right angle triangle
raTri = RightAngleTriangle(3, 4)
print('\nRight angle triangle')
print('Dimensions:',raTri.a, ',',
raTri.b, ',', raTri.c)
print('Perimeter =',raTri.perimeter())
print('Area =',raTri.area())
Output:
Scalene triangle Dimensions: 5.342 , 10.4 , 12.9 Perimeter = 28.642 Area = 26.76677 Right angle triangle Dimensions: 3 , 4 , 5.0 Perimeter = 12.0 Area = 6.0Back to function list
tuple()
Syntaxtuple([iterable]) Parameter: itearble: Optional, a sequence, collection or an iterator object. Examples: tuple('Spam') ⇒ ('S', 'p', 'a', 'm') tuple({'colour':'red', 'type':'sedan'}) ⇒ ('type', 'colour') tuple() ⇒ ()
Description
The tuple() function creates a tuple object. If a parameter is provided MicroPython will attempt to convert it to a tuple. If no parameter is given then an empty tuple is returned.
If tuple() is applied to a dictionary, a tuple containing the dictionary keys will be returned.
Related functions
Back to function listtype()
Syntaxtype(object) Parameter: object: Any MicroPython object. Examples: type('Spam') ⇒ <class 'str'> type({1:'one', 2:'two'}) ⇒ <class 'dict'> class aClass: a = 'Spam' myClass = aClass() type(myClass) ⇒ <class 'aClass'>
Description
The type() function returns the type of the object. There is a more complicated version of this function also supported by MicroPython but will not be covered here.
If there is a need to check the type of an object, it is better to use the isinstance() function instead. The isinstance() function also checks if the given object is an instance of the subclass and secondly, multiple types can checked against in a single function call.
Related functions
Back to function listzip()
Syntaxzip([iterable1, iterable2, ... iterableN]) Parameters: iterable1, iterable2, ... iterableN: Zero, one or more iterables.
Description
The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterable is paired together, and then the second item in each passed iterable are paired together, etc.
If the passed iterables have different lengths, the iterable with the least items decides the length of the new iterator.
If sequences like lists, tuples, or strings are passed as arguments to zip(), then the iterables are guaranteed to be evaluated from left to right.
If other types of iterables are used such as the set type then the order of the tuples in the resultant iterator will be unpredictable.
The zip() function provides an easy way to create dictionaries. This is demonstrated in the example below.
Example 39
# Demonstrates built-in function zip()
# No arguements passed to zip()
L = list(zip())
print(L) # Returns an empty list.
# Three lists passed to zip().
# The second list has only two elements.
# The function will only return two pairs of tuples.
l1 = ['Spam', 45, 3+5j]
l2 = ['World', 6+2j]
l3 = [1, 2, 3]
L = list(zip(l1, l2, l3))
print(L)
# Demonstrating how zip() can be used
# to construct dictionaries.
key = ('one', 'two', 'three')
value = (1, 2, 3)
D = dict(zip(key, value))
print(D)
Output:
[] [('Spam', 'World', 1), (45, (6+2j), 2)] {'two': 2, 'one': 1, 'three': 3}Back to function list