Learning Python
This month I strongly considered taking a full-time position with Keane IT Services (which was recently acquired by NTT Data). Unfortunately, it turned out that role wasn’t a good fit for where I’m at professionally and the responsibilities I have for my family (but it looks like another opportunity I received might be a better fit). As part of the position, I would have needed to beef up my Python skills since one of their client’s Remote Monitoring systems uses it heavily. Not being sure of which version of Python they use, I followed the advice on the official Python site and started with the latest and greatest – version 3.2 – which represents the future of the language.
While learning, I also wanted to make a short course for my wife, because if I could teach her the basics then it would be the perfect proof that I had a handle on the core of the language. Together we successfully walked through the basics of mathematics, string operations, lists, returning values, running a program and packaging a module. I had done some things in Python before but they were mostly around debugging or updating a small section of someone else’s code (i.e. tweaked a Message consumer here, structured a SOAP call there).
Learning from existing code is definitely always the quickest way to learn for me though. To this end, Dive Into Python 3 is hands down one of the best resources other than the Python documentation or official tutorial itself, since it provides code samples. In honesty what helped me most though, was probably the free course offered by Google, which I essentially simplified and repackaged when teaching my wife at home.
After going through the course and feeling a bit confident, I was ready for my first real Python 3.2 program (other than the typical command-line testing and Hello World app). For this I decided to update the Yahoo! Weather Python SDK from 2.x to 3.x and create a Python 3 module for accessing Yahoo! Weather and wrapping their XML Web Services as JSON for consumption by a client. For the client itself, I could have easily written most of the parsing code (if not everything) in my usual manner of using client-side code (i.e. JavaScript) as much as possible then interacting with external Web Services via a server-side proxy, but just for fun and completeness of doing it all server-side I did it all Python style, including outputting the HTML to display the weather report. That way, you can interact with the “index.py” file directly from the browser as a CGI script that accepts user input via GET submitted from its form, or, interactively via the URL (the URL hacking took a bit of time to get my head around in Python).
#!/usr/bin/python -tt
######################################################
# yahoo_weather
# Grabs forecasts from the Yahoo! Weather API
# @param zip_code
# @return condition JSON
######################################################
#Step 1 - IMPORTS
import sys
import xml.etree.ElementTree as weather
from urllib.request import urlopen
WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
#Step 2 - FUNCTIONS
def weather_for_zip(zip_code):
url = WEATHER_URL % zip_code
rss = weather.parse(urlopen(url)).getroot()
forecasts = []
for element in rss.findall('channel/item/{%s}forecast' % WEATHER_NS):
forecasts.append({
'date': element.get('date'),
'low': element.get('low'),
'high': element.get('high'),
'condition': element.get('text')
})
ycondition = rss.find('channel/item/{%s}condition' % WEATHER_NS)
condition = ycondition.get('text')
temperature = ycondition.get('temp')
title = rss.findtext('channel/title').replace("Yahoo! Weather - ","")
return {
'current_condition': condition,
'current_temp': temperature,
'forecasts': forecasts,
'title': title
}
def main():
if len(sys.argv) >= 2:
print(weather_for_zip(sys.argv[1]))
else:
print("ERROR: Please enter your Zip Code when calling the program.")
#Step 3 - ACTIVATE FUNCTION
if __name__ == '__main__':
main()
Next, you can call this module from a web-accessible endpoint “index.php” as follows:
#!/usr/bin/python -tt
#Step 1 - IMPORTS
import urllib
from urllib.parse import urlparse
import yahoo_weather
#Step 2 - PROCESSING DATA
url = self.request.query_string #python2: urlparse( request.environ.get('PATH_INFO') )
if (url['zip'] != None):
weather = weather_for_zip(url['zip'])
else:
weather = "ERROR: Please enter your Zip Code when calling the program."
#Step 3 - OUTPUT
print("",weather,"")
In any case I now know there aren’t too many huge differences between Python 2.x and 3.x but there are some notable ones such as the requirements that print statements become true functions and thusly use an opening and closing parenthesis as follows:
print "some text"
becomes:
print("some text")
And other than that major bit of rocket science single quoted strings are treated as individual bytes instead of blocks of text, so for example:
list('text')
gives:
['t', 'e', 'x','t']
rather than:
['text']
meanwhile:
list("text")
would give:
["text"]
One of the best things about version 3 is that the default encoding is now UTF-8, so multi-language programming and supporting internationalization of content has never been easier.
Conclusion
Python is different from Java, PHP and Perl in many ways, but you can clearly see where the languages and communities overlap. I think that knowing just enough Perl to get myself in trouble, and being quite familiar with PHP will help me to get up to speed with modern Python development pretty quickly though, while my Java background means I can get my head around dependencies and managing the import hierarchy of modules.
If I were to go any further in my studies, I think I’d tackle the Django framework since I’ve been told by some more dedicated Python programmers that it is essential. The only issue is that as of this writing I think its still not fully ported to Python 3.x? Well, it’s worth a look anyway to get a handle on how it works, though I probably won’t be using Python much if at all in my new role, it never hurts to learn something new.
Related articles
- Learning Python (programmingbeans.wordpress.com)
- Learn Python The Hard Way 2nd Edition Released (learnpythonthehardway.org)
- Python.h Problem: No such file or directory (imiloainf.wordpress.com)
- Comparing Python JSON implementations (deron.meranda.us)
- Python – some useful links (goinggnu.wordpress.com)

Leave a Reply
No trackbacks yet.
No post with similar tags yet.
Posts in similar categories
BC$ = Behavior, Content, Money
The goal of the BC$ project is to raise awareness and make changes with respect to the three pillars of information freedom - Behavior (pursuit of interests and passions), Content (sharing/exchanging ideas in various formats), Money (fairness and accessibility) - bringing to light the fact that:
1. We regularly hand over our browser histories, search histories and daily online activities to companies that want our money, or, to benefit from our use of their services with lucrative ad deals or sales of personal information.
2. We create and/or consume interesting content on their services, but we aren't adequately rewarded for our creative efforts or loyalty.
3. We pay money to be connected online (and possibly also over mobile), yet we lose both time and money by allowing companies to market to us with unsolicited advertisements, irrelevant product offers and unfairly structured service pricing plans.

It's a bittersweet victory as I reach the end of my internship with Sony and thu...
Long before the release of the W3C's Widget specification, most modern...
The ALPHA version of SkipSearch has been released!!!
SkipSearch is a proprietary front-end to OpenRecommender, an open source recommendation engine. Its primary features include:
Easy-to-use Interface with hover-intent to reduce clicks, audio controls & shortcuts
Lightweight HTML5 / CSS3 layout
Mobile-friendly, responsive design
Schema.org properties and support for RDFa/Microformats
Import data from multiple accounts (Google/Yahoo/Microsoft/Twitter/Facebook/LinkedIN/Last.FM/StumbleUpon and other social media account integration)
Export functionality...
It is with great humility and gratitude that I announce that I have finished in the Top 10 of the Mintchip Challenge with my proposed application and idea that "A digital currency can be used for P2P barter and micropayments".
You can see the full list of finalists in the Mintchip Challenge here:
http://ideas.mintchipchallenge.com/
There were really some...
Here's an explanation of what we have today, followed by a Use-Case for my idea...
TODAY:
1. Person A is a farmer who has worked hard all season and is ready for harvest of their crops. For simplicity's sake, let's call him the "Seller", since the next step will be to sell their produce. For that they...
Since the February confirmation of the Facebook IPO, Facebook has continued to stagnate in user-base yet as an organization it holds no punches as it attempts to grow internationally, and its stock price continues to soar as Class A shares finally open up to the average person (major investment firms had first dibs at the...
The Royal Canadian Mint(RCM) has sponsored the MintChip Challenge 2012 in an effort to attract developers to the idea of developing software for the MintChip and giving away their best financial application ideas, basically, for free (on the long-shot that you are one of the few who win).
Starting April 1st, 2012, they began mailing out...
Social media has taken over the web (for now) and the name of the game is sharing, something legislation like SOPA and PIPA just didn't seem to understand. Rather than figuring out a new economic model based on the reality of sharing on the web, that rewards this type of activity (which is essentially just...
Well, I've decided to give this one away in the title, since the good folks over at ChalkGaming helped me out quite a bit while consulting with a big client who wanted to integrate Sports Stats into their Online Newspaper properties.
Requirement
Create a sports widget to display quality sports data (including: schedules, box scores, standings, betting...
This is a post to announce the ALPHA release of OpenRecommender, version 1.0.
Have you ever wondered if there was a better way to find information on the web? Before today, there has been lots of ways from targeted search to surfing aimlessly, or from social sharing via SNS platforms like Facebook or Google+ to required...
I'm looking to add a significant amount of Music data to the OpenRecommender project to power the new Music Recommendation services.
Since I couldn't find one, I feel compelled to write a side-by-side comparison between MusicBrainz (the old trusty) and the Million Song Database by LabROSA @ Columbia U. (the new kid in town). The following...
For a long time now, I've been a paying customer of SchedulesDirect, and by that token their parent company Zap2it (now a Tribune Media Services company).
Recently, I've started publishing my own personal Electronic Programming Guide (EPG) here on BCmoney MobileTV in an accessible format:
BC$ EPG
One of the secondary goals of my MobileTV project has...