I am using Python 2.7 and wrote the following:
def arithmetic(A):x=1 """ Some comments here """ if x=1:x=1elif x=2:x=2return 0
But it has the indentation issue:
if x=1:^ IndentationError: unexpected indent
So how to write comments in the function?
I am using Python 2.7 and wrote the following:
def arithmetic(A):x=1 """ Some comments here """ if x=1:x=1elif x=2:x=2return 0
But it has the indentation issue:
if x=1:^ IndentationError: unexpected indent
So how to write comments in the function?
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=1elif x==2:x=2return 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 :)