Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent and comments in function in Python

Tags:

python

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?

like image 601
CYC Avatar asked Aug 12 '15 02:08

CYC


People also ask

What is the use of comments and indentation in Python?

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.

How do you comment a function in Python?

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 “”).

How do you indent an input in Python?

Note. While you can use any number of spaces to indent a statement, the general convention is to use four spaces.

Should code comments be indented?

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).


1 Answers

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 :)

like image 103
Patrick Maupin Avatar answered Sep 20 '22 13:09

Patrick Maupin