Sunny Wang
Sunny Wang

Reputation: 51

How to add comments in Python code with break-lines?

How to add comments in Python code with break-lines? I suppose the following should not work. Is there any wrappers for Pythons that support the break-lines?

# Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

print(subtract(6, \  # = 6 - (3 * (1 + 2))
multiply(3, \  # = 3 * (1 + 2)
add(1, 2))))  # = 1 + 2

Upvotes: 0

Views: 69

Answers (1)

fsimonjetz
fsimonjetz

Reputation: 5802

There must not be any characters after \, not even whitespace. Python has implicit line continuation though, so it's possible to spread the expression over multiple lines and add comments like this (though I'm not sure if it makes the code more readable):

print(subtract(6,  # = 6 - (3 * (1 + 2))
               multiply(3,  # = 3 * (1 + 2)
                        add(1, 2)  # = 1 + 2
                       )
              )
     )

Upvotes: 3

Related Questions