Reputation: 629
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?
Upvotes: 8
Views: 8334
Reputation: 643
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
Upvotes: 1
Reputation: 8127
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 :)
Upvotes: 17
Reputation: 16423
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
Upvotes: 1