4

I was working with simple if-else statements in Python when a syntax error came up with the following code.

"""
A multi-line comment in Python
"""
if a==b:
    print "Hello World!"

"""
Another multi-line comment in Python
"""
else:
    print "Good Morning!"

This code gives a syntax error at the "else" keyword.

The following code however does not:

"""
A multi-line comment in Python
"""
if a==b:
    print "Hello World!"

#One single line comment
#Another single line comment
else:
    print "Good Morning!"

Could anyone tell me why this happens? Why does the Python interpreter not allow multi-line comments between if-else statements?

ashishbaghudana
  • 389
  • 2
  • 4
  • 13

2 Answers2

6

You're using multiline strings in your code. So you're basically writing

if a==b:
    print "Hello World!"

"A string"
else:
    print "Good Morning!"

Although Guido Van Rossum (the creator of Python) suggested to use multiline strings as comments, PEP8 recommends to use multiple single line comments as block.

See: http://legacy.python.org/dev/peps/pep-0008/#block-comments

Railslide
  • 5,344
  • 2
  • 27
  • 34
4

For what it is worth, you can get around this problem by using indentation:

a=2
for b in range(2, 4): 
    """ 
    multi-line comment in Python
    """
    if a==b:
        print "Hello World!"
        """ 
        Another multi-line comment in Python
        """
    else:
        print "Good Morning!"

... but it is not particularly pretty, imo.

As python treats triple quotes just as strings, as suggested above, the wrong indentation basically cuts the loops short and interrupts the program's flow, throwing an error on the ill-defined else statement.

So I agree with the previous Q.s and comments sentiment that multiple single line quotes are favourable.

Sonke Hee
  • 151
  • 1
  • 9