I read a little further in Hetland about
def, and found that you can self-document your functions. Though it’s not too much help in my programs so far (I don’t yet know how to make a
--help option available), but the Python interpreter turn them automagically into *nix-style man pages when you call them with
Anyway, Hello World! seems to be turning into my guinea pig of choice when it comes to learning new coding tricks, so I fiddled around some to create
#!/usr/bin/env python # hello.py v1.2.1 # Hello World! # # Changelog: # v1.2.1 (10/12/2010) + More playing around with def # + Tells user how long their name is # v1.2.0 (10/11/2010) + Now with def magic # v1.1.2 (09/19/2010) + Now ensures user enters a name # v1.1.1 (09/11/2010) + Added GPLv3 license text & changelog to comments # + Added user-visible program & (c) info # + Re-commented program, because we were all newbs once # v1.1 (08/08/2010) + Added "Press <enter>" prompt for terminal execution # - Deleted unnecessary comments # v1.0 (07/20/2010) - Initial release (My first program!) # # Copyright 2010 Benjamin Braithwaite # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # (c) info print "Hello World! v1.2.1" print "Copyright 2010 by Benjamin Braithwaite" print # get user's name name = "" while not name.strip(): name = raw_input("What is your name? ") # put user's name into template ltrs = "" def hello(name,ltrs): "Template for returning user's name in a personalized greeting." ltrs = len(name) return "Hello, %s! You have %s letters in your name." % (name,ltrs) # print user's name in a personalized greeting print print hello(name,ltrs) print # successful exit dialog raw_input("Press <enter> to exit.")
As you can see, I added a letter counter for fun. You know, to spice things up a bit! Unfortunately, it also counts spaces, so it’s not always accurate. I’m realizing that edge cases really are most of the work of coding!
Again, I’m sorry for the shortness of the commentary in my recent posts — I’ve started biking to and from work, so my time is a little more limited as far as writing is concerned. Until tomorrow, happy hacking!