A little levity for unsettled times

Statue in the dark
Photo by K. Mitch Hodge on Unsplash

As I write this in mid-October, we’re approaching the 7-month mark since the initial lockdown of the Corona Virus and there’s less than a month away from the presidential election. Everything feels serious, heavy, and draining. But wait — here’s a little fun stuff I learned in Python this past week!

I didn’t play many video games as a child (except for the original hand-held Pacman game), so it wasn’t until 2015 that I first heard of the term “Easter Egg” (as a hidden message, not the colorful egg) from the Tesla Model X. Recently I came across my first Pythonic Easter Egg and that little surprise lightened the day. I simply typed “import this” into my Jupyter notebook and got:

As a numbers geek, my second favorite Pythonic Easter Egg is:

code snippet
code snippet
A second Python Easter Egg

The second and third little surprises came about when I was comparing the code for finding a prime number in R and Python.

After writing my Python code, I checked on-line for other versions and solutions. Several people on Stackoverflow used a for/else loop and that was a new one for me. A for/else loop?!? According to my research, the clause of the loop is a lesser-known feature. This was surprise #2 and here’s how it was used:

For/Else loop in Python

After more searching in Stackoverflow, I came across a code snippet that was considered very Pythonic. Surprise #3 was the function:

Pythonic code for finding a prime number in a range

This was the first time I had seen the function used. The function accepts an iterable object (such as a list or dictionary) as an argument. If all the elements in the passed iterable are true, then the function returns true or else it returns false. If the iterable is empty then this function returns true.

Admittedly, it took me some time to work through the Pythonic version. I’m pretty sure I could not have written that on my own, but it was definitely a fun challenge to work through the sparse 3-line function. And having a little fun these days is good therapy.