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?
Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code.
Python provides an in-built feature called docstrings for commenting on modules, methods, functions, objects, and classes. They are written in the first line after defining a module, function, method, etc., using three quotation marks ('' or “”).
Note. While you can use any number of spaces to indent a statement, the general convention is to use four spaces.
Comments should align with the code they refer to, using the same indenting as the line that follows the comment. Comments should be indented with tabs (like code, not like doc blocks).
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With