[Tutor] multiline comment in Python

Jeff Shannon jeff at ccvcorp.com
Fri Sep 5 16:15:58 EDT 2003


tpc at csua.berkeley.edu wrote:
> hi Karl, I am sorry, when I said a block of code that already has print
> statements in it, I meant print statements using quotes.  Take for example
> a small program I wrote yesterday to be run from the commandline:
> 
> <code>
> #!/usr/bin/env python
> 
> def dec2hexconverter(x):
>         hexstring = hex(x).replace('0x', '').replace('L', '').upper()
>         length = len(hexstring)
>         if length == 1:
>                 hexstring = '000' + hexstring
>         """elif length == 2:
>                 hexstring = '00' + hexstring
>         elif length == 3:
>                 hexstring = '0' + hexstring"""
>         elif length == 8:
>                 hexstring = hexstring[:4] + ' ' + hexstring[-4:]
>         print hexstring
> 
> dec2hexconverter(3735928559)
> </code>
> 
> As it is, when you run it Python gives you a syntax error.  When you take
> out the triple quotes it runs just fine.  This is not the most elegant
> code, but the issue of nesting quotes remains, you cannot do so in Python
> just as you cannot nest multiline comments in Java or C.

This is actually not throwing a syntax error because of the embedded 
quotes -- it's perfectly legal to embed quote characters within a 
triple-quoted string, and indeed that's half the motivation for 
allowing triple-quoted strings -- """A bit of "this" and a bit of 
'that'""" is a perfectly legal string.

The problem here is that your string is not *actually* a comment, and 
on going through this, the parser writes code to create and then throw 
away that string.  Then you have an 'elif:' ... which is separated 
from the 'if' by a different statement, and thus is bare.  *That* is 
where your syntax error is coming from.

As others have noted, most editors will have block-comment features 
that will allow you to comment out multiple lines at once (and 
uncomment them later), so that's the "correct" way to accomplish this.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list