How to Use Python’s Most Common Data Structures

In this tutorial, we will focus on lists in Python, a versatile data structure that is especially useful in robotics for handling collections of items like sensor readings or robotic commands.

Prerequisites

Working with Lists

Let’s create a new file named robotics_lists.py inside the following folder: ~/Documents/python_tutorial.

cd ~/Documents/python_tutorial
code .

First, let’s define a list to store sensor data.

# Sensor data list
sensor_readings = [20, 55, 75, 10]
print("Initial Sensor Readings:", sensor_readings)

This list holds some dummy sensor readings.

To access an element, use its index. Here’s how you access the first and the last reading:

# Accessing elements
print("First reading:", sensor_readings[0])  # 20
print("Most recent reading:", sensor_readings[-1])  # 10

Suppose a sensor is recalibrated, and you need to update its reading:

# Updating a sensor reading
sensor_readings[2] = 80
print("Updated Readings:", sensor_readings)

Adding new sensor data as it comes can be achieved with append:

# Adding a new sensor reading
sensor_readings.append(65)
print("Readings after append:", sensor_readings)

If a sensor malfunctions, you might need to remove its data:

# Removing a sensor reading
del sensor_readings[0]  # Removing the first reading
print("Readings after deletion:", sensor_readings)

To handle each reading, say for analysis or adjustment, iterate through the list:

# Iterating through sensor readings
for reading in sensor_readings:
    print("Processing reading:", reading)

Now run the code.

1-lists

Creating a Set

Now let’s explore sets in Python. Sets are perfect for managing unique items in robotics, like tracking visited locations or unique sensor IDs.”

Create a new file named robotics_sets.py inside the following folder: ~/Documents/python_tutorial.

Type the following code into the editor.

# Creating a set of unique sensor IDs
sensor_ids = {101, 102, 103, 104}
print("Unique Sensor IDs:", sensor_ids)

Here we define a set with unique sensor IDs. Sets are great because they automatically handle uniqueness.

Now, let’s see what happens when we try to add duplicates.

# Attempting to add duplicate sensor IDs
sensor_ids.update([102, 103, 105])
print("Updated Sensor IDs:", sensor_ids)

Notice how it ignores duplicates but adds new unique items.

To add new sensor data or remove outdated ones, we use add() and discard().

# Managing sensor data
sensor_ids.add(106)
print("After adding:", sensor_ids)

sensor_ids.discard(101)
print("After discarding:", sensor_ids)

discard() is safe to use because it won’t cause an error if the item doesn’t exist, unlike remove().

We can also perform set operations like unions and intersections, useful for comparing sensor data across different sets.

# Set operations with sensor data
another_set = {104, 105, 107}
print("Union:", sensor_ids.union(another_set))
print("Intersection:", sensor_ids.intersection(another_set))

These operations help determine overlaps or combining data from multiple sensor sets.

Run the script.

2-sets

You’ll observe how sets efficiently manage unique items and perform operations that are important in robotics for data handling.

Creating a Tuple

Let’s dive into tuples in Python. Tuples are immutable collections, meaning once created, you can’t change their elements, making them ideal for data that should remain constant.

Let’s create a new file named using_tuples.py inside the following folder: ~/Documents/python_tutorial.

Tuples are defined by enclosing elements in parentheses. Let’s create one now.

# Creating a tuple
coordinates = (10, 20, 30)
print("Coordinates:", coordinates)

This tuple could represent coordinates in 3D space, for example.

Tuples are great for accessing elements by index:

# Accessing tuple elements
print("X-coordinate:", coordinates[0])
print("Z-coordinate:", coordinates[-1])

Tuples can also hold mixed data types and can be unpacked into separate variables, which is very handy in many situations.

# Tuple with mixed data types and unpacking
info_tuple = ("Item", 150, 23.99)
name, quantity, price = info_tuple
print("Unpacked:", name, quantity, price)

Save your file, and let’s run it to demonstrate these tuple features.

3-tuples

You can see how we use tuples to store and handle data securely and efficiently.

Creating a Dictionary

Let’s explore how to create and use dictionaries in Python. Dictionaries are a fundamental data structure for storing key-value pairs, which is useful for managing complex information.

Let’s start by creating a new file named creating_a_dictionary.py inside the following folder: ~/Documents/python_tutorial.

Here’s how to define a dictionary with curly braces, using keys and values.

Type the following code into the editor:

# Creating a dictionary
robot_parts = {'wheels': 4, 'motors': 2, 'sensors': 5}
print("Robot Parts Dictionary:", robot_parts)
print("")

This example creates a dictionary to track robot components.

Now, let’s make a more complex dictionary, including lists and other dictionaries as values.

# Dictionary with various data types
robot_specs = {
    'name': 'AutomaticAddison Robot',
    'parts': robot_parts,
    'features': ['autonomous', 'solar-powered', 'waterproof'],
    'dimensions': {'height': 120, 'width': 75, 'weight': 150}
}
print("Robot Specifications Dictionary:", robot_specs)
print("")

To access or modify dictionary data, reference the keys.

# Accessing and modifying dictionary values
print("Robot Height:", robot_specs['dimensions']['height'])
print("")
robot_specs['speed'] = '25 km/h'
print("Updated Robot Specifications:", robot_specs)
print("")

# Removing an item
del robot_specs['speed']
print("After deletion:", robot_specs)
print("")

Finally, dictionaries can be traversed using loops to access all keys, values, or both.

# Looping through a dictionary
for key, value in robot_specs.items():
    print(key, ":", value)

Now, let’s run the script to see how dictionaries function.

4-dictionary-1
4-dictionary-2
4-dictionary-3

You’ll observe how effectively dictionaries store and manage complex data.

That’s a quick guide on creating and using dictionaries in Python. 

Thanks for following along with me, and I’ll see you in the next tutorial.

Keep building!

How to Make Decisions in Code Using Python

In this tutorial, we are going to learn how to use if-else statements in Python to make decisions. This is a core concept in robotics, where your robot needs to decide its actions based on sensor inputs and internal states. 

Prerequisites

Working with if-else Statements

Let’s get started by opening your code editor and creating a new file named robot_decision_making.py inside the following folder: ~/Documents/python_tutorial.

Type the following code:

# if-else statement for robot movement
obstacle_detected = True

if obstacle_detected:
    print("Stop or change direction.")
else:
    print("Continue moving forward.")

In this script, our robot checks if there’s an obstacle. If obstacle_detected is True, the robot will stop or change direction. Otherwise, it will keep moving forward.

1-obstacle-detected

Now, let’s simulate more complex decision-making with an elif statement, useful for handling different types of sensors.

# Using elif for sensor-based conditions
sensor_reading = 'low_battery'

if sensor_reading == 'obstacle':
    print("Avoid obstacle.")
elif sensor_reading == 'low_battery':
    print("Return to charging station.")
else:
    print("Normal operation.")

This script helps a robot decide actions based on its sensor readings, whether to avoid obstacles, recharge, or proceed with normal tasks.

2-return-to-charging-station

We can also nest if-else statements to handle hierarchical decisions.

# Nested if-else for more detailed decision-making
if sensor_reading == 'obstacle':
    distance = 5  # distance to obstacle in meters
    if distance < 1:
        print("Immediate stop.")
    else:
        print("Prepare to change direction.")
else:
    print("Continue exploration.")

This approach lets our robot make more nuanced decisions based on the distance to an obstacle.

3-continue-exploration

To manage multiple conditions simultaneously, like combining sensor checks and operational states, we use logical operators.

# Logical operators for complex conditions
battery_level = 20  # percentage
if sensor_reading == 'obstacle' and battery_level > 50:
    print("Navigate around the obstacle.")
elif sensor_reading == 'obstacle' and battery_level <= 50:
    print("Return to base for recharge.")
else:
    print("Continue on current path.")

This script demonstrates how our robot can decide whether to navigate around obstacles or return to base for a recharge based on its battery level.

4-continue-on-current-path

Working with if-elif Statements

In this tutorial, we’re going to dive deeper into using if-elif statements in Python to handle multiple conditions more efficiently. This is important for making your programs smarter and more responsive to a range of inputs.

Let’s start by creating a new file called robot_decision_system.py inside the following folder: ~/Documents/python_tutorial.

If-elif statements allow our robots to evaluate multiple conditions and react appropriately, which is important for tasks like navigation and interaction.

Here is an example with a robot deciding how to move based on sensor data.

# Robot movement decision system
obstacle_type = 'wall'

if obstacle_type == 'wall':
    print("Turn around")
elif obstacle_type == 'small object':
    print("Go over")
elif obstacle_type == 'gap':
    print("Stop and find another path")
else:
    print("Clear path, continue moving")

In this script, the robot checks the type of obstacle and decides its action. The if-elif chain stops checking after it finds a true condition.

5-turn-around

To add more complexity, we’ll integrate a power check.

# Power-aware robot decision system
battery_level = 20  # percentage

if obstacle_type == 'wall' and battery_level > 20:
    print("Turn around")
elif obstacle_type == 'small object' and battery_level > 10:
    print("Go over")
elif obstacle_type == 'gap':
    print("Stop and find another path")
else:
    print("Low power: Return to base")

You can see how the robot’s decision-making adjusts based on the obstacle type and battery level. This method is efficient for guiding a robot’s actions.

6-low-power-return-to-base

Implementing Comparison Operators

Let’s open your code editor and create a new file named comparison_operators.py inside the following folder: ~/Documents/python_tutorial.

Comparison operators compare two values and return a Boolean value, either True or False. They’re useful for directing the flow of logic in programs, particularly in if statements.

Let’s take a look at each of the primary comparison operators.

# Equal to
print("10 == 10:", 10 == 10)  # Outputs True

# Equal to
print("10 == 5:", 10 == 5)  # Outputs False

# Not equal to
print("10 != 5:", 10 != 5)    # Outputs True

# Less than
print("5 < 10:", 5 < 10)      # Outputs True

# Greater than
print("10 > 5:", 10 > 5)      # Outputs True

# Less than or equal to
print("5 <= 5:", 5 <= 5)      # Outputs True

# Greater than or equal to
print("10 >= 5:", 10 >= 5)    # Outputs True
7-implementing-comparison

These examples show how we can evaluate basic numerical comparisons.

Let’s apply these in a practical scenario, like a robotic sensor reading that determines if an action is needed.

# Robot sensor threshold check
sensor_threshold = 10
sensor_reading = 12

if sensor_reading >= sensor_threshold:
    print("Sensor threshold exceeded, take action.")
else:
    print("Sensor levels normal, no action required.")

In this script, we check if a sensor reading exceeds a set threshold, a common task in robotic programming.

8-take-action

Comparison operators aren’t limited to numbers. Let’s look at how they work with strings.

# String comparison
print("'abc' < 'def':", 'abc' < 'def')  # Outputs True
9-compare-string

This example demonstrates that ‘abc’ is less than ‘def’ based on alphabetical order, similar to how words are ordered in a dictionary.

That’s it! Keep building!

How to Create Basic Programs Using Python

In this tutorial, we are going to build basic programs using Python.

Prerequisites

  • You have completed this tutorial.
  • I am using VS Code for my Python development environment, but you are free to use any development environment you wish.

Build a Basic Calculator

Let’s start by building a basic calculator. This exercise will help you understand how to handle user input and perform basic arithmetic operations in Python.

Open a new terminal window, and move to the directory where we will store our code.

cd ~/Documents/python_tutorial

I will open VS Code.

code .

Right-click in the Explorer pane and select “New File”.

Name the file basic_calculator.py, and press Enter.

First, let’s ask the user to input two numbers. Type the following lines:

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

These commands prompt the user for input, converting the input into floating point numbers for arithmetic operations.

Next, we need to ask the user to choose the operation. Add this line:

operation = input("Choose the operation (+, -, *, /): ")

Now, we’ll use conditional statements to perform the operation selected by the user.

if operation == '+':
    result = num1 + num2
elif operation == '-':
    result = num1 - num2
elif operation == '*':
    result = num1 * num2
elif operation == '/':
    if num2 != 0:
        result = num1 / num2
    else:
        result = "Error! Division by zero."
else:
    result = "Invalid operation selected."

print(result)

This if-else structure helps our calculator decide what to do based on the user’s choice.

After writing the code, save your file. Let’s now run our program to see how it works.

Enter the numbers and the operation when prompted. 

Watch as your program calculates and displays the result.

1-basic-calculator

Making Your Program Executable

Let’s see how to make basic_calculator.py executable. We will do this directly from the command line. This will enhance your workflow by allowing you to run your Python scripts without explicitly calling the Python interpreter each time.

Let’s begin by opening the basic_calculator.py script we created in the previous lecture. Once open, we need to add a shebang line at the very top of the file.

Type the following line as the first line in your file:

#!/usr/bin/env python3

This shebang line tells the system that this script should be run using Python 3, which we’ve installed on our machine. Make sure this line is at the top, before any other code.

After adding the shebang, save your file. 

The next step is to make the script executable. We’ll do this using the terminal.

Open your terminal in Visual Studio Code by going to View -> Terminal

Navigate to the directory where your  basic_calculator.py file is located. Now, type the following command:

cd ~/Documents/python_tutorial
chmod +x basic_calculator.py 

This command changes the file’s permissions, making it executable. 

Now, you can run your Python script directly from the command line.

To run your script, simply type the following in your terminal:”

./basic_calculator.py 
2-make-program-executable

Notice how we didn’t have to type ‘python3’ before our script name. The system recognizes it as an executable file and runs it using the Python interpreter specified in the shebang line.

Go ahead and test different inputs to see how your calculator works now as an executable script.

Doing Basic Calculations

Let’s explore how to perform basic calculations in Python. We’ll cover addition, subtraction, multiplication, division, and a bit about modulus operations.

Let’s get started by opening your code editor. We’ll create a new file named basic_calculations.py.

In this file, we’ll write small code snippets to demonstrate each type of calculation. First, let’s start with addition.

# Addition
print("Addition of 5 + 3 is:", 5 + 3)

This will output the sum of 5 and 3. Now, let’s do subtraction.

# Subtraction
print("Subtraction of 5 - 3 is:", 5 - 3)

Next, we have multiplication.

# Multiplication
print("Multiplication of 5 * 3 is:", 5 * 3)

And then division.

# Division
print("Division of 5 / 3 is:", 5 / 3)

Division in Python gives you a float. If you need the integer quotient, you can use the floor division operator.

# Floor Division
print("Floor division of 5 // 3 is:", 5 // 3)

Lastly, let’s look at the modulus operation, which gives the remainder of a division.

# Modulus
print("Modulus of 5 % 3 is:", 5 % 3)

After typing these examples, save your file. Now, let’s run this script to see the output of these basic calculations.

3-basic-calculations

You should see the results for each operation displayed in the terminal. These operations are fundamental to programming and form the basis for more complex algorithms.

Working with Random Values

Let’s learn how to work with random values in Python. This capability is essential for simulating uncertainty in robotics applications and for creating varied testing scenarios.

Let’s start by opening your code editor. We’ll create a new file and name it working_with_random.py.

To generate random numbers, Python provides a module named random. First, we need to import this module.

import random

Let’s begin with generating a random integer. We’ll use the randint function, which returns an integer between the specified range.

# Generate a random integer between 1 and 10
random_integer = random.randint(1, 10)
print("Random integer between 1 and 10:", random_integer)

Next, we’ll generate a random float. The random function returns a floating-point number between 0.0 and 1.0.

# Generate a random float
random_float = random.random()
print("Random float between 0.0 and 1.0:", random_float)

Sometimes, you may want to generate a float within a different range. You can do this by multiplying the result of random().

# Generate a random float between 0.0 and 5.0
random_float_in_range = random.random() * 5
print("Random float between 0.0 and 5.0:", random_float_in_range)

We can also pick a random element from a list. Let’s create a list of colors and select one randomly.

# Pick a random element from a list
colors = ['red', 'blue', 'green', 'yellow']
random_color = random.choice(colors)
print("Random color selected:", random_color)

Lastly, if you want to shuffle the items in a list randomly, you can use the shuffle method.

# Shuffle a list
random.shuffle(colors)
print("Shuffled colors:", colors)

After entering these examples, don’t forget to save your file. Now, let’s run the script to see how random values are generated.

4-random-variables

You’ll see the outputs for each of the random operations we scripted. This functionality is invaluable for creating diverse and dynamic environments in simulations and tests.

Using Nan and Infinity

Let’s explore how to work with NaN (Not a Number) and Infinity in Python. These are special floating-point values that you may encounter in numerical computations, especially when dealing with undefined or unbounded values.

Let’s start by opening your code editor. We’ll create a new file and name it nan_and_infinity.py.

To use NaN and Infinity, Python doesn’t require any special imports as they are part of the standard float type. Let’s start with Infinity.

# Positive Infinity
positive_infinity = float('inf')
print("Positive Infinity:", positive_infinity)

# Negative Infinity
negative_infinity = float('-inf')
print("Negative Infinity:", negative_infinity)

These lines create variables for positive and negative infinity. Operations with these values yield predictable results, following rules of mathematical infinity.

Next, we have NaN. It’s a special value used to denote that a result of a computation cannot be defined in meaningful terms.

# NaN example
not_a_number = float('nan')
print("Example of NaN:", not_a_number)

Let’s see some operations with NaN. Any operation involving NaN typically results in NaN, indicating an invalid result.

# Operations with NaN
print("NaN added to a number:", not_a_number + 5)
print("NaN multiplied by a number:", not_a_number * 2)

Interestingly, comparing NaN with anything, even itself, is always false. This is useful for checking if a value is NaN.

# Checking if a value is NaN
print("Is NaN equal to NaN?:", not_a_number == not_a_number)

To properly check for NaN, we use the math.isnan() function from the math module.

import math
print("Using math.isnan() to check NaN:", math.isnan(not_a_number))

Now, let’s run the script to see how NaN and Infinity behave in Python.

5-nan-infinity

You’ll see the outputs for each operation, illustrating how special floating-point values like NaN and Infinity are handled in Python.

That’s it. You have gotten some good experience building programs in Python to perform fundamental calculations.

Thank you, and I’ll see you in the next tutorial.

Keep building!