Reputation: 5135
Usually I can make comment with #
or """
for multiline comments. But in the following cases,
if i > 0:
if (df.loc[i, 'data'] <= level1) and \ # Comment
(df.loc[i - 1, 'data'] > level1) and \ # Comment
not ideal_state:
ideal_state_time = df.loc[i,'data']
ideal_state = True
I got the error
File "<ipython-input-24-07959bc4f436>", line 121
if (df.loc[i, 'data'] <= level1) and \ # Comment
^
SyntaxError: unexpected character after line continuation character
What is going on? What's wrong with commenting after the slash? I put the slash there because otherwise it will return an error.
Upvotes: 0
Views: 689
Reputation: 725
You can try replacing \
(back-slashes) with ()
(brackets) as shown below
if( (df.loc[i, 'data'] <= level1) and # Comment
(df.loc[i - 1, 'data'] > level1) and # Comment
not ideal_state
):
ideal_state_time = df.loc[i,'data']
ideal_state = True
You can see in PEP8, it's recommended to use brackets
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read())```
Upvotes: 1
Reputation: 356
the backslash "\" is the line continuation character. i.e
print "massive super long string that doesn't fit" + \
"on a single line"
only newline charecters/whitespace are allowed after it.
Upvotes: 0
Reputation: 1042
The backslash allows your if to span multiple lines, as it says something like "ignore the upcoming char (newline)"
your interpreter reads it like this:
if (df.loc[i, 'data'] <= level1) and # Comment (df.loc[i - 1, 'data'] > lev...
And then your interpreter is right, your comment sign does not belong there.
Line continuations may never carry comments.
You're allowed to comment again after not ideal_state:
Upvotes: 0