Raspberry Pi + Python = an automated coin flipper

I’ve been playing around with my Raspberry Pi for a couple of weeks now. “Playing” is definitely the right word!

So far, I’ve ‘built’ a case for it from a rather nasty grey plastic box I sourced from a local electrical retailer, figured out how to create SD cards so I can boot it into Linux (the beta of the Debian ‘Wheezy’ release being my current choice), got it working on my home network (and out onto the internet), installed a FORTRAN compiler and most excitingly of all, started to learn Python.

I think I’m going to like Python. It seems to have all the good bits from languages like C, Pascal, LISP, Perl and Java, with none of the bad bits such as pointer arithmetic, garbage collection and the like.

Anyway, here’s a screenshot of my very first working Python program (other than “hello world”, of course). It doesn’t do anything very clever I’m afraid, but it’s enabled me to get the hang of the basics of the language’s syntax and figure out how to use SPE, one of the many development environments that are available.

How to flip a coin in Python

If the weather stays as lousy as it is at the moment this weekend, I’m going to attempt something a little more ambitious next. I have a Star Trek game from a 1979 issue of Computing Today, written in a dialect of BASIC, that I’m going to try to convert into a working (and hopefully reasonably elegant) Python equivalent.

Beam me up, Scotty …

Posts Tagged with…

Reader Comments

  1. Xavier Francisco

    Try to read a few examples of python code, to help you program with a more pythonic style. For example, that while loop there, will burn some programmer’s eyes. You should use a for loop with xrange(or range if you’re using Python 3). Also careful with the random module. Using random.choice for a binary choice is a bad idea, just because it’s so slow…

    A simple one liner that you can study, that will give you the heads of a amount of flips:
    get_heads = lambda times: bin(random.getrandbits(times)).count(‘1’)

    It’s not likely the fastest solution out there, but it might help you along the ride 😉

    • tim

      I think perhaps my language was a little clumsy.

      What I was trying to get at is that you don’t have to explicitly allocate and deallocate dynamic memory as you would in a language like C. The garbage collection capabilities documented in http://docs.python.org/library/gc.html supplement the automatic reference counting strategy of python, rather than being mandatory.

Your thoughts?