Python Data Structures
Python provides built-in data structures that are essential for storing and manipulating data. The three fundamental data structures in Python are lists, dictionaries, and tuples.
Lists
A list is a collection of items that are ordered and changeable. It allows duplicate items and is represented by square brackets ([]). You can access and modify elements in a list using indexing and slicing.
1import numpy as np
2
3# Create a list
4numbers = [1, 2, 3, 4, 5]
5
6# Access elements in the list
7print(numbers[0]) # Output: 1
8
9# Modify elements in the list
10numbers[2] = 9
11print(numbers) # Output: [1, 2, 9, 4, 5]
12
13# Iterate over the list
14for number in numbers:
15 print(number)
xxxxxxxxxx
coordinates[0] = 7
import numpy as np
# Create a list
numbers = [1, 2, 3, 4, 5]
# Access elements in the list
print(numbers[0]) # Output: 1
# Modify elements in the list
numbers[2] = 9
print(numbers) # Output: [1, 2, 9, 4, 5]
# Iterate over the list
for number in numbers:
print(number)
# Create a dictionary
person = {
"name": "John",
"age": 30,
"occupation": "Engineer"
}
# Access values in the dictionary
print(person["name"]) # Output: John
# Modify values in the dictionary
person["age"] = 35
print(person) # Output: {'name': 'John', 'age': 35, 'occupation': 'Engineer'}
Build your intuition. Click the correct answer from the options.
What is the purpose of a Python list?
Click the option that best answers the question.
- To store and manipulate ordered collection of items
- To perform mathematical operations on numbers
- To represent a single value
- To create a dictionary-like data structure
Python Control Flow
In Python, control flow refers to the order in which the code is executed. It allows us to make decisions, repeat actions, and control the flow of our program based on certain conditions.
Conditional Statements
Conditional statements are used to execute different blocks of code based on a specified condition. The most commonly used conditional statement is the if
statement.
1# Example of an if statement
2speed = 50
3
4if speed > 60:
5 print('Slow down!')
6else:
7 print('You are within the speed limit.')
Loops
Loops are used to repeatedly execute a piece of code until a certain condition is met. There are two types of loops in Python: for
loops and while
loops.
1# Example of a for loop
2for i in range(5):
3 print(i)
4
5# Example of a while loop
6count = 0
7
8while count < 5:
9 print(count)
10 count += 1
Control Flow
Control flow allows us to alter the execution path of our program. This can be achieved using conditional statements and loops. By controlling the flow of our program, we can make decisions and perform actions based on specific conditions.
1# Example of control flow
2import cv2
3import numpy as np
4
5# Define a function to control the robot
6
7def robot_control(distance):
8 if distance < 10:
9 print('Stop! Obstacle ahead!')
10 elif distance >= 10 and distance < 30:
11 print('Slow down, obstacle approaching')
12 else:
13 print('Continue moving')
14
15robot_control(15)
In the example above, the robot_control
function takes in a distance
parameter and uses conditional statements to control the behavior of the robot based on the distance.
xxxxxxxxxx
import cv2
import numpy as np
# Define a function to control the robot
def robot_control(distance):
if distance < 10:
print('Stop! Obstacle ahead!')
elif distance >= 10 and distance < 30:
print('Slow down, obstacle approaching')
else:
print('Continue moving')
robot_control(15)
Are you sure you're getting this? Click the correct answer from the options.
What statement is used to execute different blocks of code based on a specified condition?
Click the option that best answers the question.
- if statement
- for loop
- while loop
- else statement
File Handling in Python
File handling is an essential skill in Python programming, especially in robotics and computer vision applications. It allows us to read data from files, write data to files, and manipulate files to store and retrieve information.
Reading Files
To read data from a file, we can use the open()
function in Python. The open()
function takes two arguments: the name of the file and the mode ('r' for read mode). Here's an example:
1# Open the file in read mode
2file = open('data.txt', 'r')
3
4# Read the contents of the file
5content = file.read()
6
7# Close the file
8file.close()
9
10# Print the contents of the file
11print(content)
In the example above, we use the open()
function to open the file named 'data.txt' in read mode. Then we use the read()
method to read the contents of the file and store it in the content
variable. Finally, we close the file using the close()
method and print the contents.
Writing Files
To write data to a file, we can use the open()
function with the mode set to 'w' for write mode. Here's an example:
1# Open the file in write mode
2file = open('output.txt', 'w')
3
4# Write data to the file
5file.write('Hello, world!')
6
7# Close the file
8file.close()
In the example above, we use the open()
function to open the file named 'output.txt' in write mode. Then we use the write()
method to write the string 'Hello, world!' to the file. Finally, we close the file using the close()
method.
File Manipulation
Python provides various methods and functions for file manipulation. For example, we can check if a file exists using the exists()
function from the os.path
module:
1import os
2
3# Check if a file exists
4if os.path.exists('data.txt'):
5 print('File exists!')
6else:
7 print('File does not exist!')
We can also delete a file using the remove()
function from the os
module:
1import os
2
3# Delete a file
4os.remove('output.txt')
These are just a few examples of file handling operations in Python. With file handling skills, you can efficiently work with data stored in files and perform operations required for robotics and computer vision applications.
Build your intuition. Fill in the missing part by typing it in.
To read data from a file, we can use the open()
function in Python. The open()
function takes two arguments: the name of the file and the mode ('r' for read mode). Here's an example:
1# Open the file in ___________ mode
2file = open('data.txt', 'r')
3
4# Read the contents of the file
5content = file.read()
6
7# Close the file
8file.close()
9
10# Print the contents of the file
11print(content)
In the example above, we use the open()
function to open the file named 'data.txt' in read mode.
Write the missing line below.
Python Modules and Libraries for Robotics
Python provides a rich ecosystem of modules and libraries that are commonly used in the field of robotics. These modules and libraries offer powerful functionality and make it easier to develop robotics applications. Let's take a look at a few of the most commonly used modules and libraries:
NumPy
NumPy is a fundamental library for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. NumPy is widely used in robotics for tasks such as data manipulation, linear algebra calculations, and numerical simulations. Here is an example of using NumPy to calculate the mean and standard deviation of an array:
1import numpy as np
2
3# Python code that uses the NumPy library
4
5# Create a numpy array
6arr = np.array([1, 2, 3, 4, 5])
7
8# Perform operations on the array
9mean = np.mean(arr)
10std_dev = np.std(arr)
11
12# Print the results
13print('Mean:', mean)
14print('Standard Deviation:', std_dev)
OpenCV
OpenCV (Open Source Computer Vision Library) is a popular computer vision library that provides a wide range of functions and tools for image and video processing. It allows you to capture and analyze images and videos, perform various image transformations, detect objects, and more. OpenCV is extensively used in robotics for tasks such as object recognition, motion detection, and visual servoing.
ROS
ROS (Robot Operating System) is a flexible framework for writing robot software. It provides a collection of libraries and tools that help you build complex robotic systems. ROS enables communication between different components of a robot, such as sensors, actuators, and control algorithms. It also provides a wide range of pre-built packages and algorithms that can be easily integrated into your robotics projects.
These are just a few examples of the modules and libraries available in Python for robotics. By leveraging these powerful tools, you can accelerate the development of robotics applications and focus on solving higher-level problems.
xxxxxxxxxx
import numpy as np
# Python code that uses the NumPy library
# Create a numpy array
arr = np.array([1, 2, 3, 4, 5])
# Perform operations on the array
mean = np.mean(arr)
std_dev = np.std(arr)
# Print the results
print('Mean:', mean)
print('Standard Deviation:', std_dev)
Try this exercise. Is this statement true or false?
Module is imported with the import
keyword in Python.
Press true if you believe the statement is correct, or false otherwise.
Generating complete for this lesson!