การเขียนโปรแกรม Python สำหรับงานเทคโนโลยี

Data types, control flow, functions, modules, files and debugging

Last updated:

Overview

Outside the flight controller itself, Python is the language UAS technologists use most: reading flight logs, computing energy, planning routes, commanding simulated drones over MAVLink and analysing imagery. The code is easy to read, runs without a compile step and has libraries for almost everything. This unit summarises six essentials, data types, control flow, functions, modules and environments, files, and debugging, as a reference while you study and build projects.

Data types and data structures

A variable is a name bound to a value, and Python works out the type at run time. The basic types are int (integers), float (real numbers), str (text) and bool (True or False). Four structures hold many values:

TypeCharacterDrone example
listOrdered, changeableA list of waypoints
tupleOrdered, fixedOne position (lat, lon)
dictName-value pairs, looked up by nameAircraft data {"id": "RSU-01", "cruise_ms": 8.0}
setUnique, unorderedMAVLink message IDs seen so far

A float is stored in binary, so a value like 0.1 is not exact; compare with math.isclose() rather than ==. Put units in names, such as altitude_m or speed_ms, to avoid mixing metres with feet or km/h with m/s.

Control flow

Programs decide with if/elif/else and repeat with for (over existing data) or while (until a condition becomes false). Indentation marks each block; PEP 8 uses four spaces per level. Condition order changes the answer, for example the "critical" battery check must come before "low", and values exactly on a boundary must always be tested. The pattern zip(a, a[1:]) pairs neighbouring items, such as the start and end waypoints of each leg or two consecutive log rows.

Functions

A function is a box that takes inputs and returns a result. A good function does one job, has a name that says what it does, carries a docstring describing inputs and outputs, and does not secretly change outside variables. When it receives an impossible value, such as a battery at 120%, it should raise an exception such as ValueError and let the caller decide, rather than guess. Callers handle it with try/except naming the expected error type, never a bare except: that hides real problems.

Example: energy used, from a voltage and current log

Assume a log records a 6S pack's voltage and current every 60 s for 6 minutes. We want the energy used in Wh by integrating power P = V × I over time with the trapezoidal rule (average the power at two neighbouring points and multiply by the interval).

samples = [  # (time_s, volts, amps) every 60 s, assumed values
    (0, 25.1, 20.2), (60, 24.8, 21.0), (120, 24.5, 21.5), (180, 24.3, 22.1),
    (240, 24.1, 22.4), (300, 23.9, 23.0), (360, 23.7, 23.6),
]


def energy_wh(rows):
    """Integrate power over time with the trapezoidal rule; return watt-hours."""
    total_j = 0.0
    for (t0, v0, i0), (t1, v1, i1) in zip(rows, rows[1:]):
        total_j += (v0 * i0 + v1 * i1) / 2 * (t1 - t0)
    return total_j / 3600


used = energy_wh(samples)
print(f"energy used: {used:.1f} Wh")
print(f"share of a 222 Wh pack: {used / 222:.0%}")
energy used: 53.5 Wh
share of a 222 Wh pack: 24%

Power rises from about 507 W to 559 W because current climbs as voltage sags. Total energy is about 53.5 Wh, roughly 24% of a 222 Wh pack in 6 minutes. Before using it on real logs, test the function on a known answer: a constant 600 W for 3,600 s must give exactly 600 Wh.

Modules, libraries and virtual environments

A module is a .py file whose functions other files import. The standard library ships with Python, for example math, csv, json and pathlib. Third-party libraries such as pandas, matplotlib and pymavlink are installed with pip.

A virtual environment is a folder that isolates one project's libraries. Create it with python -m venv .venv and activate it every time you work. List libraries and versions in requirements.txt so teammates can build an identical environment. The programme's lessons use Python 3.12 to 3.14.

Files and data

Open files with with open(...) so they close even if an error occurs, and always pass encoding="utf-8" so Thai text survives on other machines. The csv module returns every value as text, so convert numbers yourself, or use pandas, which converts types and adds summary tools. JSON suits structured settings and results. Use pathlib.Path so file paths work on both Windows and Linux, and never modify the original data file; always write results to a new one.

Debugging

Debugging is finding and fixing the cause of wrong behaviour. Read a traceback from the bottom up: the last line gives the error type and message, such as TypeError when text is multiplied by a float, and the lines above show the file and line where it happened. Useful tools:

  • Print intermediate values with f-strings; print(f"{t0=} {v0=}") shows both names and values.
  • The built-in debugger: call breakpoint() to pause and step through lines, or use the VS Code debugger.
  • assert and pytest to check known answers and boundary values automatically.
  • The logging module for long-running programs, such as companion-computer scripts, recording time and severity.

The rule is to reproduce the problem with a small data set first, then fix one thing at a time.

Common pitfalls

  • Installing libraries globally instead of in a venv, or forgetting to activate it.
  • Comparing floats with ==.
  • Passing degrees to trigonometric functions that expect radians.
  • Using a list as a default argument, so values persist between calls.
  • Omitting encoding="utf-8" when reading or writing files.
  • Bare except: that hides real errors.
  • Passwords in source code; read them from environment variables instead.

Continue in the lessons

Key references

  1. Python Software Foundation. The Python tutorial (Python 3.14 documentation). link
  2. Matthes, E. (2023). Python crash course (3rd ed.). No Starch Press.
  3. Downey, A. B. (2024). Think Python: How to think like a computer scientist (3rd ed.). O’Reilly. link
  4. van Rossum, G., Warsaw, B., & Coghlan, A. (2001). PEP 8 – Style guide for Python code. link
  5. Python Software Foundation. venv — Creation of virtual environments (Python 3.14 documentation). link
  6. Python Software Foundation. Floating-point arithmetic: Issues and limitations. In The Python tutorial (Python 3.14 documentation). link

Used in courses

How to cite this page

Drone Institute, Rangsit University. (2026). การเขียนโปรแกรม Python สำหรับงานเทคโนโลยี. In UAS Technology Knowledge Hub (B.Tech.). https://rsu-uat.pk-research.work/en/kb/new/prog-python/