Skip to main content

Hurrah-ndom inventions

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:

  1. I’ve got Pi(3) brain
  2. Why-Fi-ght the Wi-Fi?

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.

...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.
...lists items in this directory.  Anything there?  No, so let's create our Python application file.
...touch command creates an empty file.  Let's create one called ''.  The '.py' extension generally means it is a Python file.
...check that the 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.

...opens the 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.

...runs the application code stored in the 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"]
    "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
You may have also spotted the ’#’ symbol whenever we were making comments in the code.  These lines are ignored by Python, but are useful to us humans who quite often forget what we've written (or eaten that morning).

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:


  1. Thanks for the fun toot-oreo.

    Python seems so ugly at times like:
    print(OBJECTS[randint(0, len(OBJECTS)-1)])

    I compulsively modified rosie:
    """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) )

  2. and then I "read the manual"...

    from random import choice

    print( choice(OBJECTS) )

    a double thank you - I can be patient... or will be a patient.

    1. 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.


Post a Comment


LoRa-Wan Kenobi

In the regurgitated words of Michael Bublé: It's a new dawn .  It's a new day .  It's a new Star Wars film .  For me .  And I'm (George Lucas, and I'm) feeling good .  Unfortunately for Canadian Mike, the Grammy that year was won by the novelty disco classic with the famous refrain: We love IoT, even in Planet Tatooine * . *Not true. Clearly, the Star Wars producers didn't sincerely mean the last Jedi the previous time around.  Return of the Jedi, released during the decade that spearheaded cultural renaissance 2.0 with the mullet and hair-metal , was less economic with the truth.  Either way, we're going to take inspiration from the impressive longevity of the money-spinning space-opera and reboot our franchise with some Jedi mind tricks.  Except this particular flick doesn't require an ever-growing cast of unrecognisable characters, unless ASCII or UTF counts.  In place of an ensemble gathering of Hollywood stars and starlets, we will b

Battle of BLEtain

The trolling . The doxing . An army of perplexing emojis. And endless links to the same - supposedly funny - viral video of a cat confusing a reflection from a dangling key for a golden hamster, while taking part in the mice bucket challenge. Has social media really been this immense force for good? Has it actually contributed significantly to the continued enlightenment of the human (or feline) race? In order to answer these poignant existential questions about the role of prominent platforms such as Critter, StinkedIn and Binterest, employing exceptional scientific rigour equal to that demonstrated by Theranos , we're going to set up a ground-breaking experiment using the Bluetooth Low Energy feature of MicroPython v1.12, and two ESP32 development boards with inexplicable hatred for one another.  And let them hurl quintessentially British expressions (others call them abuse) at each other like two Wiltshire residents who have had their internet access curbed by the co

Hard grapht

You would all be forgiven for assuming that bar , pie and queue line are favourite pastimes of the British .  Yet, in fact – yes, we did learn this back in GCSE maths – they are also mechanisms through which meaningless, mundane data of suspect origin can be given a Gok Wan -grade makeover, with the prime objective of padding out biblical 187-page PowerPoint presentations and 871-page Word reports (*other Microsoft productivity tools are available).  In other words, documents that nobody has the intention of ever reading.  But it becomes apparent over the years; this is perhaps the one skill which serves you well for a lifetime in certain careers.  In sales.  Consultancy.  Politics.  Or any other profession in which the only known entry requirement is the ability to chat loudly over a whizzy graph of dubious quality and value, preferably while frantically waving your arms around. Nevertheless, we are acutely conscious of the fact that we have spent an inordinate amount