Functions in Python for IoT Systems
Definition
A function in Python is a block of reusable code that performs a specific task. Functions help
modularize code, making it easier to read, maintain, and reuse.
Syntax
To define a function:
def function_name(parameters):
# code block
return value
Types of Functions
1. Built-in Functions: Provided by Python (e.g., print(), len(), type())
2. User-defined Functions: Created by the user using the def keyword.
Parameters and Return Values
Functions can accept parameters (inputs) and return values (outputs).
Example:
def add(a, b):
return a + b
Scope
Variables defined inside a function have local scope and are not accessible outside the function.
Global variables can be accessed using the global keyword.
Use Cases in IoT Applications
1. Sensor data processing
2. Device control logic
3. Communication protocols
4. Data logging and analysis
Example:
def read_temperature(sensor):
temp = sensor.get_data()
return temp
Exercise
1. Write a function to calculate the average of three sensor readings.
2. Create a function that turns on a device if temperature exceeds a threshold.
3. Define a function that logs data to a file.