Control & Math

14. Control Statements

Control statements change the normal execution of a program.

break

Stops a loop immediately.

for i in range(10):

if i == 5:
break

print(i)

continue

Skips the current repetition and continues with the next one.

for i in range(10):

if i == 5:
break

print(i)

pass

Does nothing. It is used as a placeholder when you want to write the code later.

def my_function():
pass

if True:
pass

15. Math Functions

MicroPython includes built-in mathematical functions and a math module for more advanced calculations.

Built-in math functions

FunctionDescriptionExample
abs()Absolute valueabs(-5) → 5
round()Rounds a numberround(3.7) → 4
min()Smallest valuemin(2, 5, 1) → 1
max()Largest valuemax(2, 5, 1) → 5
sum()Adds list valuessum([1,2,3]) → 6

Example:

numbers = [10, 20, 30]

print("Total:", sum(numbers))
print("Minimum:", min(numbers))
print("Maximum:", max(numbers))

Using the math module

Import the module before using its functions.

import math

print(math.sqrt(25)) # Square root
print(math.pow(2, 3)) # Power
print(math.pi) # Pi
print(math.floor(4.8)) # Round down
print(math.ceil(4.2)) # Round up

Some useful trigonometric functions include:

import math

angle = math.radians(90)

print(math.sin(angle))
print(math.cos(angle))