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:
pass15. Math Functions
MicroPython includes built-in mathematical functions and a math module for more advanced calculations.
Built-in math functions
| Function | Description | Example |
|---|---|---|
abs() | Absolute value | abs(-5) → 5 |
round() | Rounds a number | round(3.7) → 4 |
min() | Smallest value | min(2, 5, 1) → 1 |
max() | Largest value | max(2, 5, 1) → 5 |
sum() | Adds list values | sum([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 upSome useful trigonometric functions include:
import math
angle = math.radians(90)
print(math.sin(angle))
print(math.cos(angle)) 