Before I ever looked at computer programming, words such “beautiful code” gave me only the vaguest sense of what people were talking about. What does that mean ? Is it merely efficient code ? Or does it refer to a sort-of Eureka type solution to a programming problem? Now that I’ve spent a couple of months looking at Python (BTW, I passed both my Python and PHP final exams this week – yeah !!!), I’m beginning to understand not only what beautiful code may be but also appreciate the clarity of Python.
When I was in high school, I took a year of BASIC programming. One of the few things I could remember from that was code like this.
10 FOR A = 1 TO 10
20 PRINT “GREAT CODE”
30 NEXT A
This always made complete sense. It’s so simple. You use a variable (A) to count loops till your variable reaches a certain value (10) and ends. The next level for me was stuff like this:
10 FOR A = 1 TO 10
20 PRINT “THIS IS GREAT CODE EXAMPLE NO.”, A
30 NEXT A
In this example, you use the variable A for more than just counting loops. It’s also part of the output. Both methods are clean and simple solutions and give the beginner a sense of how to think like a programmer.
Yesterday, I came across a piece of code in O’Reilly’s “Python Cookbook” using List Comprehensions.
thenewlist = [ x + 23 for x in the oldlist if x > 5 ]
Even if you don’t know Python and don’t know what exactly a list is, it should be immediately clear what’s going on here. For me, it was a Eureka type moment realizing how simple and powerful Python is, if you can pack a loop, a condition, and an expression (?) into one line of code. I got a real kick out of this.
1 response so far ↓
paddy3118 // June 6, 2008 at 5:44 am |
(No space between ‘the’ and ‘oldlist’
- Paddy.