Noah
Noah

Reputation: 614

In Python, how are triple quotes (""") considered comments by the IDE?

My CS teacher told me that """ triple quotations are used as comments, yet I learned it as strings with line-breaks and indentations. This got me thinking - does python completely triple quote lines outside of relevant statements?

"""is this completely ignored like a comment"""

or, is the computer actually considering this?

Upvotes: 21

Views: 41135

Answers (3)

Tony Cardinal
Tony Cardinal

Reputation: 25

I found this information on the web. I'm paraphrasing here: While Python primarily uses the # symbol for single-line comments, triple quotes can be used to create multi-line comments. The words, etc inside these qoutes are strings that aren't assigned to a variable, so they don't have any effect on the program's execution.....So I suppose they are strings which are not assigned to any variables

Upvotes: -1

BTables
BTables

Reputation: 4833

As someone else already pointed out, they are indeed strings and not comments in Python. I just wanted to add a little more context about your question of "is the computer actually considering it?"

The answer is yes, since it isn't a comment. Take the below code for example:

def my_func():
"""
Some string
"""
    print("Hello World!")
my_func()

Trying to run this will actually produce a syntax error because of the indentation. Compare that to an actual comment:

def my_func():
# Some comment
    print("Hello World!")
my_func()

This runs fine and prints Hello World!.

Upvotes: 6

ThePyGuy
ThePyGuy

Reputation: 18426

Triple quoted strings are used as comment by many developers but it is actually not a comment, it is similar to regular strings in python but it allows the string to be in multi-line. You will find no official reference for triple quoted strings to be a comment.

In python, there is only one type of comment that starts with hash # and can contain only a single line of text.

According to PEP 257, it can however be used as a docstring, which is again not really a comment.

def foo():
    """
    Developer friendly text for describing the purpose of function
    Some test cases used by different unit testing libraries
    """
    ...  # body of the function

You can just assign them to a variable as you do with single quoted strings:

x = """a multi-line text
enclosed by
triple quotes
"""

Furthermore, if you try in repl, triple quoted strings get printed, had it really been a comment, should it have been printed?:

>>> #comment
>>> """triple quoted"""
'triple quoted'

Upvotes: 22

Related Questions