How to Process User Input and Strings in Python

In this tutorial, we are going to explore how to accept user input in Python, an essential skill for programming interactive robots. Whether you’re controlling a robot remotely or setting up initial parameters, user input is key to dynamic interactions.

Prerequisites

Accepting User Input

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

First, we’ll create an interface for a user to input commands to control a robot.

# Command input for robot control
command = input("Enter command for the robot (move, stop, turn): ").lower()
if command == 'move':
    print("Robot moving...")
elif command == 'stop':
    print("Robot stopping...")
elif command == 'turn':
    direction = input("Which direction to turn (left or right)? ").lower()
    print(f"Robot turning {direction}")
else:
    print("Unknown command.")

This script allows users to control basic robot movements via simple text commands.

Next, we might need to gather numerical data, such as setting a speed or defining a movement angle.

# Setting robot speed
speed = input("Enter robot speed (1-10): ")
speed = int(speed)  # Convert the input from string to integer
print(f"Robot speed set to {speed}.")

Here, the user sets the robot’s speed, demonstrating how to handle numerical input.

Robots often work with sensors that require calibration or thresholds to be set by the user. Let’s simulate setting a sensor threshold.

# Setting sensor threshold
threshold = input("Set sensor threshold (e.g., temperature, distance): ")
threshold = float(threshold)
print(f"Sensor threshold set at {threshold} units.")

This example takes a threshold value for perhaps a temperature or distance sensor and applies it to the robot’s sensor settings.

We can also allow the user to input multiple configurations at once, useful for setting up initial parameters or during maintenance checks.

# Accepting multiple configuration values
configurations = input("Enter robot configurations separated by commas (arm length, camera resolution, wheel diameter, torso width): ")

config_list = configurations.split(',')

print("Robot configurations set:", config_list)

This allows the user to input a list of configuration values, which are then processed and applied to the robot.

Make sure to save your file. Now, let’s run the script to see how these input mechanisms work in action.

1-accepting-user-input

You’ll see how the program interacts with user commands and inputs, allowing for flexible and dynamic control of robot functions.

Using String Functions

Let’s explore string functions in Python and how they can be applied in robotic projects to manipulate and process textual data.

Strings in Python come with a variety of built-in functions that allow us to perform common operations. 

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

message = "Hello, World!"
print(len(message))  # Output: 13
print(message.upper())  # Output: HELLO, WORLD!
print(message.lower())  # Output: hello, world!

The len() function returns the length of the string, while upper() and lower() convert the string to uppercase and lowercase, respectively.

In robotic applications, string functions can be used to process and interpret textual commands or messages.

For example, let’s say we have a robot that receives commands in the format “COMMAND:PARAMETER”. We can use the split() function to extract the command and parameter.

command_str = "MOVE:FORWARD"
command, parameter = command_str.split(":")
print("Command:", command)  # Output: MOVE
print("Parameter:", parameter)  # Output: FORWARD

The split() function splits the string based on the specified delimiter (in this case, “:”) and returns a list of substrings.

String functions can also be used for data validation and cleaning. Let’s say we have a sensor that reads distance measurements as strings, but sometimes it includes unwanted characters.

distance_str = "12.5m"
distance_str = distance_str.strip("m")
distance = float(distance_str)
print("Distance:", distance)  # Output: 12.5

The strip() function removes the specified characters from the beginning and end of the string, allowing us to extract the numeric value and convert it to a float.

Another useful string function is replace(), which replaces occurrences of a substring with another substring.

status_message = "Error: Sensor disconnected"
status_message = status_message.replace("Error", "Warning")
print(status_message)  # Output: Warning: Sensor disconnected

This can be handy when processing log messages or status updates from robotic systems.

String functions offer a wide range of possibilities for manipulating and processing textual data in robotic applications. They can be used for parsing commands, extracting information from sensor readings, formatting messages, and much more.

2-using-string-functions

That’s it for this tutorial on using string functions in robotics. Thanks, and I’ll see you in the next tutorial.

Keep building!

How to Use Python Range and Iterator Functions

In this tutorial, we are going to learn how to use iterators in Python, which allow us to traverse through sequences of elements efficiently.

Prerequisites

Working with Iterators

Create a program called working_with_iterators.py inside the following folder: ~/Documents/python_tutorial.

Let’s create a list and an iterator from it using the iter() function.

my_list = [1, 2, 3, 4, 5]
my_iterator = iter(my_list)

We can traverse the iterator using the next() function.

print(next(my_iterator))  # Output: 1
print(next(my_iterator))  # Output: 2
print(next(my_iterator))  # Output: 3
1-working-with-iterators

Alternatively, we can use a for loop to iterate through the elements automatically.

my_iterator = iter(my_list)  # Reset the iterator

for item in my_iterator:
    print(item)
2-working-with-iterators

It’s important to note that when there are no more elements in the iterator, a StopIteration exception is raised, signaling the end of the iteration.

Iterators are fundamental for efficient data processing in Python and are particularly useful in robotic projects when working with large datasets or sequences of data.

Working with Ranges

Let’s dive into the concept of ranges in Python, which provide a convenient way to generate sequences of numbers.

Create a program called working_with_ranges.py inside the following folder: ~/Documents/python_tutorial.

Let’s start by creating a simple range using the range() function.

my_range = range(5)
print(my_range)  # Output: range(0, 5)

The range() function generates a sequence of numbers starting from 0 (by default) and ending at the specified number (exclusive).

We can convert the range to a list to see its elements.

my_list = list(my_range)
print(my_list)  # Output: [0, 1, 2, 3, 4]
3-working-with-ranges

The range() function can also take additional arguments to specify the start value and the step size.

my_range = range(2, 10, 2)
my_list = list(my_range)
print(my_list)  # Output: [2, 4, 6, 8]
4-working-with-ranges

Here, the range starts from 2, ends at 10 (exclusive), and increments by 2 in each step.

Ranges are commonly used in for loops to iterate a specific number of times.

for i in range(5):
    print(i)
5-working-with-ranges

This loop iterates 5 times, with the variable i taking values from 0 to 4.

Ranges are memory-efficient because they generate numbers on-the-fly rather than storing them in memory. This makes them useful when working with large sequences of numbers.

In robotic projects, ranges can be used for tasks like iterating over a sequence of angles for a robotic arm or generating a series of time steps for a simulation.

That’s it for this tutorial on ranges. Thanks, and I’ll see you in the next tutorial.

Keep building!

How to Write Loops in Python

In this tutorial, we are going to learn how to write loops in Python. Loops are a key tool for iterating over sequences and automating repetitive tasks.

Prerequisites

You have completed this tutorial: How to Use Python’s Most Common Data Structures.

Writing For Loops

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

First, let’s demonstrate a simple for loop with a list of colors.

Type the following code into the editor:

# Simple for loop with a list
colors = ['red', 'green', 'blue', 'yellow']
for color in colors:
    print("Color:", color)

This loop prints each color in our list, showing how for loops process elements one by one.

Next, we’ll use a for loop with the range() function, which generates a sequence of numbers.

# For loop with range
for i in range(4):  # Generates numbers from 0 to 3
    print("Number:", i)

Here, range(4) produces numbers from 0 to 3, and we print each one.

For loops can also iterate over strings, treating each character as an item.

# Iterating over a string
for char in 'robotics':
    print("Character:", char)

This prints each character in ‘robotics’.

Next, let’s loop through a dictionary of robot parts.

# Looping through a dictionary
robot_parts = {'wheels': 4, 'motors': 2, 'sensors': 5}
for part, quantity in robot_parts.items():
    print("Part:", part, "Quantity:", quantity)

Using .items() allows us to print both keys and values.

Lastly, we’ll explore nested for loops, useful for processing multi-dimensional data.

# Nested for loops
for outer in range(3):
    for inner in range(3):
        print("Position:", outer, inner)

This generates a grid of positions from (0, 0) to (2, 2).

Save your file, and let’s run it to see these for loops in action.

1-writing-for-loops-1
2-writing-for-loops-2
3-writing-for-loops-3
4-writing-for-loops-4
5-writing-for-loops-5

You can see how for loops effectively handle various data structures.

Writing While loops

Let’s explore how to effectively use while loops in Python. These loops are essential for executing code repeatedly based on a condition.

Open your code editor and start a new file, writing_while_loops.py inside the following folder: ~/Documents/python_tutorial.

First, let’s look at a basic while loop that prints numbers from 0 to 4.

# Basic while loop
count = 0
while count < 5:
    print("Count:", count)
    count += 1

This loop increments ‘count’ each time, stopping when it reaches 5.

Next, we’ll use a while loop to handle user input. This loop will continue until ‘quit’ is entered.

# While loop with user input
user_input = ""
while user_input.lower() != 'quit':
    user_input = input("Enter 'quit' to exit: ")
    print("You entered:", user_input)

This demonstrates a loop that runs based on user interaction.

Finally, let’s use the ‘break’ statement to exit a loop prematurely.

# Using break in a while loop
count = 0
while True:
    if count == 5:
        break
    print("Looping:", count)
    count += 1

print("")

This loop runs indefinitely but breaks when ‘count’ reaches 5.

Save your file, and then let’s run the script to see these while loops in action.

6-writing-while-loops-1
writing-while-loops-2
writing-while-loops-3

You’ll see how each while loop works, demonstrating their versatility and power in handling different types of data structures.

We’ve covered basic to advanced uses of while loops, showing how they control flow in programs. Thanks, and I’ll see you in the next tutorial.

Keep building!