Python Refresher

Introduction to Python

While C is the undisputed king of writing firmware for microcontrollers, Python is the dominant language for Data Science, Machine Learning, and rapid prototyping.


Why Python in This Workshop?

In the Analog Data Edge AI toolchain, Python serves two distinct roles:

  1. On your computer (The Host): You will use Python to collect raw sensor data, train Machine Learning models (using TensorFlow/Keras), and analyze the results.
  2. On the microcontroller (The Edge): You can use MicroPython to rapidly prototype hardware interactions on the ESP32 or Raspberry Pi Pico without waiting for C code to compile.

What Is Python?

Python is a high-level, interpreted language.

  • High-level: It abstracts away memory management. You don't need to worry about pointers, malloc(), or declaring variable types.
  • Interpreted: You don't "compile" a Python script into a binary .bin file. Instead, a program called the Python Interpreter reads your script line-by-line and executes it on the fly.

Your First Python Program

python
1# This is a comment
2print("Hello, World from Python!")
3
4# Variables don't need explicit types
5message = "Learning AI on the Edge"
6device_count = 5
7is_active = True
8
9print(f"Status: {message}. Devices: {device_count}")

Python vs C — Quick Comparison

If you're coming from the C refresher, here is how the two languages contrast:

FeatureC / C++ (Embedded)Python
ExecutionCompiled to machine code beforehand.Interpreted line-by-line at runtime.
TypingStatically typed (int x = 5;).Dynamically typed (x = 5).
Memory ManagementManual (You allocate and free memory).Automatic (Garbage Collector handles it).
SyntaxUses curly braces { } and semicolons ;.Uses indentation (spaces/tabs) to define blocks.
SpeedExtremely fast. Close to hardware.Slower. Great for high-level logic, not microsecond timing.

The Indentation Rule

In C, whitespace doesn't matter. In Python, indentation is syntax.

C code:

c
1if (status == 1) {
2printf("OK"); // Works, even though it's ugly
3}

Python code:

python
1if status == 1:
2 print("OK") # The indent (usually 4 spaces) is REQUIRED

Indentation Error

If you forget the indent, Python will throw an IndentationError and crash.


In the next sections, we'll quickly review Python's data structures, which are heavily used when manipulating datasets for Machine Learning.

Previous
Interview Questions