Python Refresher
Functions & Modules
As your scripts grow larger than 50 lines, you need to start organizing your code into reusable blocks (Functions) and separate files (Modules).
Defining Functions
In Python, you define a function using the def keyword.
Remember: Python uses indentation to know what code belongs inside the function. Unlike C, there are no { } curly braces!
1# Define a function that takes two arguments2def calculate_area(width, height):3 area = width * height4 return area56# Call the function7rect_area = calculate_area(10, 5)8print(f"The area is {rect_area}")Default Arguments
Python allows you to set default values for arguments. If the user doesn't provide them, the default is used.
1def greet(name, greeting="Hello"):2 print(f"{greeting}, {name}!")34greet("Alice") # Prints: Hello, Alice!5greet("Bob", greeting="Hi") # Prints: Hi, Bob!Type Hinting (Modern Python)
Unlike C, Python doesn't force you to declare types, but modern Python heavily encourages Type Hinting. This helps your IDE (like VS Code) catch bugs before you even run the script.
1# The '-> float' hints that this function returns a float2def calculate_area(width: float, height: float) -> float:3 return width * height*args and **kwargs
Sometimes you don't know how many arguments a user will pass.
*argsallows passing an infinite number of regular arguments (as a Tuple).**kwargsallows passing an infinite number of named arguments (as a Dictionary).
1def print_sensors(*args, **kwargs):2 print("Standard Sensors:", args)3 print("Special Sensors:", kwargs)45# Call it with whatever we want!6print_sensors("BME280", "MPU6050", external="GPS_NEO6M", active=True)7# Output:8# Standard Sensors: ('BME280', 'MPU6050')9# Special Sensors: {'external': 'GPS_NEO6M', 'active': True}Lambda Functions (Anonymous Functions)
For very simple, one-line mathematical operations, Python provides lambda functions. You will see these heavily in Data Science when modifying Pandas DataFrames.
1# A normal function2def square(x):3 return x ** 245# The exact same function as a Lambda6square_lambda = lambda x: x ** 278print(square_lambda(5)) # Prints 25Modules and the Standard Library
A huge part of Python's power is that it comes with "batteries included"—a massive standard library of code already written for you. You bring this code into your script using the import keyword.
Importing built-in modules
1import math2import time34# Using the math module5root = math.sqrt(64)6print(f"Square root is {root}")78# Using the time module to pause the script9print("Wait for 2 seconds...")10time.sleep(2)11print("Done!")Importing Specific Functions
If you only need one specific function from a module, you can import just that part to save typing.
1from datetime import datetime23# Now we don't need to type datetime.datetime.now()4current_time = datetime.now()5print(f"Current time: {current_time}")Using pip to Install External Libraries
The standard library is great, but the true power of Python lies in its ecosystem of third-party packages (like numpy, tensorflow, or pyserial).
You install these packages from the terminal using pip (Python Installer Package).
Open your terminal and run:
pip install pyserial
Now, in your Python script, you can use it to read data directly from an Arduino or ESP32 plugged into your computer!
1import serial2import time34# Open the serial port (Change 'COM3' to '/dev/ttyUSB0' on Linux)5# Make sure the baud rate matches your microcontroller!6try:7 ser = serial.Serial('COM3', 115200, timeout=1)8 time.sleep(2) # Wait for the connection to settle9 10 print("Reading data from microcontroller:")11 for _ in range(5):12 # Read a line, decode the bytes to a string, and strip the \n13 line = ser.readline().decode('utf-8').strip()14 if line:15 print(f"Received: {line}")16 17 ser.close()18 19except serial.SerialException as e:20 print(f"Could not open serial port: {e}")(This exact script is how you gather raw sensor data from an ESP32 to train an Edge AI model!)

