Why the colon?

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jun 28 20:38:00 EDT 2002


Erv Young <res04ft9 at gte.net> wrote:

: 1. def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
: 2.     while 1:
: 3.         ok = raw_input(prompt)
: 4.         if ok in ('y', 'ye', 'yes'): return 1
: 5.         if ok in ('n', 'no', 'nop', 'nope'): return 0
: 6.         retries = retries - 1
: 7.         if retries < 0: raise IOError, 'refusenik user'
: 8.         print complaint

: where I have added line numbers for the sake of the discussion.  I
: understand the colons in the middle of lines 4, 5, and 7 as statement
: separators.  Makes perfect sense.

Hello!

Colons are really used for the beginning of blocks.  In lines 4, 5,
and 7, the example is using a shortcut --- if the block is just one
line long, it can be placed on the same line for brevity.  The code
could have been reformatted as:

###
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
     while 1:
         ok = raw_input(prompt)
         if ok in ('y', 'ye', 'yes'):
             return 1
         if ok in ('n', 'no', 'nop', 'nope'):
             return 0
         retries = retries - 1
         if retries < 0:
             raise IOError, 'refusenik user'
         print complaint
###

which should be treated equivalently.


Note that the one-liner shortcut doesn't work for more than one level
of block nesting, to avoid language abuse.  That is, something like:

###
>>> try: if 42 == 42: print "ok"
  File "<stdin>", line 1
    try: if 42 == 42: print "ok"
          ^
SyntaxError: invalid syntax
###

is immediately flagged as a SyntaxError.  Thank goodness.  *grin*


If you'd like to delve into the reference material about this, you can
look at:

    http://www.python.org/doc/ref/compound.html


Hope this helps!




More information about the Python-list mailing list