7

I am using Python 2.7 and wrote the following:

def arithmetic(A):
    x=1
"""
Some comments here
"""  
    if x=1:
        x=1
    elif x=2:
        x=2
    return 0

But it has the indentation issue:

    if x=1:
    ^
IndentationError: unexpected indent

So how to write comments in the function?

CYC
  • 619
  • 1
  • 5
  • 13

3 Answers3

17

The """ xxx """ is a docstring. Yes, it can be used as a comment, but it winds up being part of the actual code, so it needs to be indented:

def arithmetic(A):
    x=1
    """
    Some comments here
    """  
    if x==1:
        x=1
    elif x==2:
        x=2
    return 0

If you use line-oriented comments starting with #, those are not part of the actual code, so their indentation doesn't matter.

One nice thing about docstrings is that tools can use them, for example, to display information about functions. If you've ever used help(some_function) at the Python command prompt, you have seen a docstring.

In fact, if you load your function into an IDE, and then type help(arithmetic), you can see "Some comments here".

I modified your code slightly, because in Python, = is for assignment, and you must use == in your if statement to check for equality.

So the code will compile and run as-is, but note that only setting x to 1 if x is already equal to 1 won't actually do anything :)

Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42
1

In Python comments need to have same alignment as other code block, e.g.

def arithmetic(A):
    x=1
    """
    Some comments here
    """  
    if x=1:
        x=1
    elif x=2:
        x=2
    return 0

And usually people use # for inline comment e.g.:

def func(a):
    a = 5
    # I am a comment
    c = 6
number5
  • 15,913
  • 3
  • 54
  • 51
  • That's not quite true. The comment doesn't really need to have the same indentation as the function (though I suppose it makes it easier to know that the comment is part of the function) The docstring (""" in first line) does need to be aligned – Ray Salemi Sep 18 '17 at 19:59
1

CYC,

Comments in python use either the hash symbol # for single line comments and triple quotes for multi-line comments The thing about the multi-line comments is they are sometimes finicky and must be indented or you can get this error

See Way to create multiline comments in Python?

Please also note many python style guides and projects normally use # for comments. Many text editors and IDEs provide shortcuts for commenting blocks of texts

Community
  • 1
  • 1
Linkx_lair
  • 569
  • 1
  • 9
  • 21