What is that “else” in a for loop? And that “else” in an exception handler?
for _ in : ... else: # nobreak ... try: ... except: ... else: # noexcept ...
To be honest, IMO it is best to avoid for / else completely.
Have you ever written something like this?
fname = 'movie.avi' if fname.endswith('avi') or fname.endswith('mp4'): print("It's a movie.")
endswith also accepts a tuple. Just saying.
fname = 'movie.avi' if fname.endswith(('avi', 'mp4')): print("It's a movie.")
Meaning: if it ends as ‘
avi‘ or ‘
This also works with
startswith, of course.
Thanks to one of my students, Marton Sz. who solved one of his exercises using this trick.
Working with JPG files, PIL drops the following error:
Python PIL : IOError: decoder jpeg not available
sudo pip uninstall PIL sudo apt-get install libjpeg8-dev sudo pip install PIL
I wrote a script in Eclipse-PyDev that prints some text with accented characters to the standard output. It runs fine in the IDE but it breaks in the console:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 11: ordinal not in range(128)
This thing bugged me for a long time but now I found a working solution.
Insert the following in your source code:
import sys reload(sys) sys.setdefaultencoding("utf-8")
I found this trick here. “This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.”
Here is the classical “Hello, World!” script in Python. It can be used as a template for writing a new script:
#!/usr/bin/env python # DESCRIPTION: hello world # DATE: 2010.09.21. (yyyy.mm.dd.) print "Hello, World!"
Tip: If you want to insert source code in your blog at WordPress.com, check out this post: Code » Posting Source Code.
Update (20110503): For a more professional template, see this post, where Guido tells us how he writes his main() functions.