Like humans, robots need to be intelligent. Rational. Trustworthy.
But that sounds way too complicated, and more importantly, extremely boring. So let’s make them do random stuff instead, and learn a bit about programming on the Pi along the way.
Here, we’ll write a little Python program to allow Rosie to make random suggestions. Specifically, we want her to tell us what we should be inventing next.
You will need to have these:
- Raspberry Pi 3, and Raspbian running on SDHC card
- A computer from which you are connecting to the Raspberry Pi remotely
You will need to have done these things:
You will need to do this:
- Create a Python application and use the random module
- Populate your lists with words (be creative!)
- Run the application and (possibly) be amused by the results
What do you get after all this?
We learnt previously that Operating Systems - in our case the Linux-based Raspbian OS - allow us to interact with hardware. But the OS alone won't provide Rosie with any real intelligence. She'll in fact just sit there, unloved.. doing nothing. Zero. Nada.Now, drum roll please... Enter the real guardians of the entire galaxy. Computer Programs (or code, or scripts, or software, or applications, or whatever else people like to call them). These things contain rules and logic - described in computer languages - that allow us to process input, and afterwards, provide (hopefully useful) output.
Like actual languages (English, español, 日本語, русский + hundreds more), there are many different Programming Languages which are ways in which to write programs. They all have strange names, like C, C++, PHP and Java. We will use one called Python for Rosie. It's widely used. It's powerful. And - rather helpfully - it's already there on Raspbian OS, ready to be used.
And just to prove that we can start to make use of Rosie's brain, we will create an amazingly useful program. Actually, let's not. Let's create a silly little program - and it really is little with less than 20 lines of code - that randomly selects words from some lists and presents them back to us as a world-changing suggestion. Is it actually of any use? Most likely not.
But on second thoughts… Rosie might actually need to make random choices sometimes. Like where to go if she’s stuck or bored. Or what shapes to throw on the dance floor. In a way, just like humans.
This is simply too much detail:
As they say, let's cut to the chase. This is the Python code that we will attempt to run on the Pi:But hang on a second. WHERE? HOW?
Python applications consist of files that contain - guess what? - Python code. So let's get back to the SSH terminal that we started during our previous post and create the Python file that we need.
pwd...checks that we are in the /home/pi directory (the home directory of the 'pi' user)
cd rosie...changes to the 'rosie' directory we created previously. This is where we'd like to store this Python application.
ls...lists items in this directory. Anything there? No, so let's create our Python application file.
touch rosie_random.py...touch command creates an empty file. Let's create one called 'rosie_random.py'. The '.py' extension generally means it is a Python file.
ls...check that the rosie_random.py file has been created
Great! We now have our file, but it's empty (we did warn you about this). Let's use our old friend 'nano' to edit it.
nano rosie_random.py...opens the rosie_random.py file using the nano text editor. We used this when editing the Wi-Fi configuration file, remember?
Now copy and paste the 16 lines of code from above and paste them into the nano window. On Putty, a 'right click' on the mouse allows you to paste the text that you have just copied. If successful, your nano editor should look like this:
Once you're happy with the lines you've just pasted in, save the file and exit nano using control-x (control and x keys pressed together), 'y' key at next prompt and 'enter' when confirming the filename.
We're all set to go. Let's run the program using Python* and see what happens.
*We will be using Python version 2 (Python 2) in this series. We'll move onto using the latest and greatest version of Python (Python 3) at the start of the next series. Python 2 won't be around for much longer.
python rosie_random.py...runs the application code stored in the rosie_random.py file using Python
Tip: Pressing the 'up' or 'down' arrow keys will allow you to cycle through previous commands you have already executed. Useful, when you want to quickly see Rosie's other suggestions.
There! A Python program has suddenly made Rosie very useful. A 'banana polishing three-wheeled eel' will change lives for the better, and win you the Nobel Prize.
But what was it that we just copied and pasted? How did the code work? Let's step through each bit.
from random import randint
We import Python modules and their functions whenever we want to recycle bits of existing code. Here, we want to use the randint() function from the random module. Someone has kindly written these modules for us and made them available for use in Python - it would be ungrateful not to use them.
OBJECTS = ["banana", "squirrel", "fire", "ice-cream", "coconut"] ACTIVITIES = ["munching", "farting", "prodding", "detecting", "polishing"] GADGETS = [ "robotic squirrel", "mechanical dinosaur", "three-wheeled eel", "rechargeable owl", "battery-powered raccoon" ]
Next, we set up three list data structures in which to store our words. This will be our data. Feel free to modify and add words as you please.
print("Silly human, invent me a") print(OBJECTS[randint(0, len(OBJECTS)-1)]) print(ACTIVITIES[randint(0, len(ACTIVITIES)-1)]) print(GADGETS[randint(0, len(GADGETS)-1)])
Lastly, we will use the print() function to display a random word from each list on-screen. But, actually, there’s a few more things going on here:
- len() function is used to establish how many words are stored in each list
- Subtracting one from the len() result is required as 0 actually points to the first position (word) in the list. Therefore, the last position is number of words - 1.
- randint() function is then used to generate a random number (also called integer) between the first and last positions of the words in the lists. This will be the position of the chosen word in the list.
- And finally, the words are retrieved from the lists using their positions
We admit it. This application is pointless. It's daft. We could've come up with those suggestions ourselves. But we now know how to create a Python application and run it on the Pi. And this, is making Rosie - and the Pi - ever more useful.
Even more reading:
The Python random function is described in official Python documentation:https://docs.python.org/3/library/random.html
Thanks for the fun toot-oreo.
ReplyDeletePython seems so ugly at times like:
print(OBJECTS[randint(0, len(OBJECTS)-1)])
I compulsively modified rosie:
[Code]
"""Module to randomise silly inventions"""
# Import the randint function from the random module
from random import randint
# Populate some lists with words
OBJECTS = ["banana", "squirrel", "fire", "ice-cream", "coconut"]
ACTIVITIES = ["munching", "farting", "prodding", "detecting", "polishing"]
GADGETS = [
"robotic squirrel",
"mechanical dinosaur",
"three-wheeled eel",
"rechargeable owl",
"battery-powered raccoon"
"one-eyed rosie"
]
# Define a randListElement(list)
def randListElement(sourcelist):
return sourcelist[randint(0,len(sourcelist)-1)]
# Randomise the output
print("Silly human, invent me a")
print( randListElement(OBJECTS) )
print( randListElement(ACTIVITIES) )
print( randListElement(GADGETS) )
[/code]
and then I "read the manual"...
ReplyDeletefrom random import choice
print( choice(OBJECTS) )
a double thank you - I can be patient... or will be a patient.
Hi there. Thanks for this! I never knew there was a choice() function hidden away in the 'random' module. It sure tidies this up a bit.
Delete