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!

python
1# Define a function that takes two arguments
2def calculate_area(width, height):
3 area = width * height
4 return area
5
6# Call the function
7rect_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.

python
1def greet(name, greeting="Hello"):
2 print(f"{greeting}, {name}!")
3
4greet("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.

python
1# The '-> float' hints that this function returns a float
2def 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.

  • *args allows passing an infinite number of regular arguments (as a Tuple).
  • **kwargs allows passing an infinite number of named arguments (as a Dictionary).
python
1def print_sensors(*args, **kwargs):
2 print("Standard Sensors:", args)
3 print("Special Sensors:", kwargs)
4
5# 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.

python
1# A normal function
2def square(x):
3 return x ** 2
4
5# The exact same function as a Lambda
6square_lambda = lambda x: x ** 2
7
8print(square_lambda(5)) # Prints 25

Modules 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

python
1import math
2import time
3
4# Using the math module
5root = math.sqrt(64)
6print(f"Square root is {root}")
7
8# Using the time module to pause the script
9print("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.

python
1from datetime import datetime
2
3# 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:

bash
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!

python
1import serial
2import time
3
4# 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 settle
9
10 print("Reading data from microcontroller:")
11 for _ in range(5):
12 # Read a line, decode the bytes to a string, and strip the \n
13 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!)

Previous
Data Structures