5

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?

2
  • 3
    """This is a string, not a comment""" Commented Jan 29, 2015 at 10:26
  • How do you write a multi-line comment in Python? Multi-Line Comments in Python Commented Jan 29, 2015 at 10:32

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.