Eric Florenzano posted a meme challenge today, to which I'd like to propose a counter challenge to all python-related snippet posters:
Post your snippets in a form compatible with Python 3 if at all possible.
Many small examples of code are posted each day and often they can be written with Python 3+ in mind. Doing so will encourage people to think about the easy things - like print is now a function rather than a statement, or that xrange has mercifully been renamed range - they need to be mindful of.
- Implement a program that takes in a user's name and their age, and prints hello to them once for every year that they have been alive.
- Post these rules, the source code for your solution, and the following list (with you included) on your blog.
- Bonus points if you implement it in a language not yet seen on the following list!
name = input('Please enter your name: ') age = int(input('Please enter your age: ')) for i in range(age): print ("%2d) Hello, %s" % (i, name))
Incidentally it would not have been possible to (easily) rewrite his meme-code in a sensible 2+3 compatible manner without prefacing the Python 3 code with something like this:
import sys if sys.version < '3': input = raw_input range = xrange
Encapsulating such differences in a block allows for quick and easy removal for that sunny day when more code than not is available on Python 3+.
In practice I've found that most of my modules do not need such compatibility shims - the same code runs on Python 2 and 3 without special acrobatics.
My Counter Challenge
Install Python 3 without overwriting earlier versions you may need for productive work. Be able to call up a Python 3 interpreter when you need to see what's changed, and keep a ready link to What's new in Python 3.0.
Next time you feel compelled to post an explanatory snippet, try it in 3... and adjust it to work if necessary if if possible.