This works:
s = "for x in range(5):" \
"print(x)"
exec(s)
How to add if statement to that dynamic code, something like:
s = "for x in range(5):" \
"if x>2:" \
"print(x)"
exec(s)
Above gives error:
...
for x in range(5):if x > 2:print(x)
^
SyntaxError: invalid syntax
The problem is the lack of proper indentation of the code in the string. An easy way to get it right is to enclose the properly formatted code in a triple-quoted string.
s = """
for x in range(5):
if x>2:
print(x)
"""
exec(s)
note that \ is only python's way of allowing visually continuing the same declaration at a "new line". so in practice,
s = "for x in range(5):" \
"if x>2:" \
"print(x)"
is equal to
s = "for x in range(5):if x>2:print(x)"
You will need to add actual line breaks and tabs to make the syntax valid, as such:
s = "for x in range(5):\n\tif x>2:\n\t\tprint(x)"
note that you can make it more readable if you combine \ with the above, and swapping \t with spaces, resulting in:
s = "for x in range(5):" \
"\n if x>2:" \
"\n print(x)"
(Note that to confirm with PEP-8, you should use 4 spaces per identation)
s = "for x in range(5):\n\t" \
"if x > 2:\n\t\t" \
"print(x)"
exec(s)
This will solve your problem.
The reason for getting error is ignoring the python indentation rule, so you need to handle them with \t.
Related
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.
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())```
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:
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.
I have several strings with \ in it. I try to not using escape characters by using the replace function like that:
string.replace("\\", "\\\\")
It does not work.
When I use string.replace("\n", "\\n") for \n directly it works.
Is there an easy working solution for that?
Important to note that replace does not act on the variable but rather returns a copy with the replacement applied See the docs:
this = "string\\string"
this.replace("\\", "")
print(this)
>"string\\string"
If you want the original string to be replaced,
this = this.replace("\\", "")
However, to convert \n -> n would require that you think differently about this. i.e. replace('\n', 'n'), as \n is a single character.
You can try this:
def test():
foo = r"this is a \\ and this is a \ "
foo = foo.replace("\\" , r'\\') # added the r to ignore string escapes as escapes
print(foo)
test()
output:
this is a \\\\ and this is a \\
Use raw strings.
r"This \ string \ includes '\'s"
Code,
Result
I want to remove the whitespace at the bracket point and the place before the percentage, how can I do that? Please can I know the simplest way to do it i dont want to over complicate the code
Build a string correctly formatted, then print it instead of using a continuation comma.
...
x = temp / 4
strx = str(x) + '%'
print "overall class grades... : " + strx
...
You can do this:
print('\nAfter the lowest mark({}) has been excluded'.format(a[0]))
I know that semicolons are unnecessary in Python, but they can be used to cram multiple statements onto a single line, e.g.
>>> x = 42; y = 54
I always thought that a semicolon was equivalent to a line break. So I was a bit surprised to learn (h/t Ned Batchelder on Twitter) that a double semicolon is a SyntaxError:
>>> x = 42
>>> x = 42;
>>> x = 42;;
File "<stdin>", line 1
x = 42;;
^
SyntaxError: invalid syntax
I assumed the last program was equivalent to x = 42\n\n. I’d have thought the statement between the semicolons was treated as an empty line, a no-op. Apparently not.
Why is this an error?
From the Python grammar, we can see that ; is not defined as \n. The parser expects another statement after a ;, except if there's a newline after it:
Semicolon w/ statement Maybe a semicolon Newline
\/ \/ \/ \/
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
That's why x=42;; doesn't work; because there isn't a statement between the two semicolons, as "nothing" isn't a statement. If there was any complete statement between them, like a pass or even just a 0, the code would work.
x = 42;0; # Fine
x = 42;pass; # Fine
x = 42;; # Syntax error
if x == 42:; print("Yes") # Syntax error - "if x == 42:" isn't a complete statement
An empty statement still needs pass, even if you have a semicolon.
>>> x = 42;pass;
>>> x
42
I am having problems with this Python program I am creating to do maths, working out and so solutions but I'm getting the syntaxerror: "unexpected character after line continuation character in python"
this is my code
print("Length between sides: "+str((length*length)*2.6)+" \ 1.5 = "+str(((length*length)*2.6)\1.5)+" Units")
My problem is with \1.5 I have tried \1.5 but it doesn't work
Using python 2.7.2
The division operator is /, not \
The backslash \ is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the "interrupted" line.
print "This is a very long string that doesn't fit" + \
"on a single line"
Outside of a string, a backslash can only appear in this way. For division, you want a slash: /.
If you want to write a verbatim backslash in a string, escape it by doubling it: "\\"
In your code, you're using it twice:
print("Length between sides: " + str((length*length)*2.6) +
" \ 1.5 = " + # inside a string; treated as literal
str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
# character, but no newline follows -> Fail
" Units")
You must press enter after continuation character
Note: Space after continuation character leads to error
cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}
0.9 * average(cost["apples"]) + \ """enter here"""
0.1 * average(cost["bananas"])
The division operator is / rather than \.
Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:
"\\ 1.5 = "`
or use a raw string
r" \ 1.5 = "
Well, what do you try to do? If you want to use division, use "/" not "\".
If it is something else, explain it in a bit more detail, please.
As the others already mentioned: the division operator is / rather than **.
If you wanna print the ** character within a string you have to escape it:
print("foo \\")
# will print: foo \
I think to print the string you wanted I think you gonna need this code:
print("Length between sides: " + str((length*length)*2.6) + " \\ 1.5 = " + str(((length*length)*2.6)/1.5) + " Units")
And this one is a more readable version of the above (using the format method):
message = "Length between sides: {0} \\ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))
This is not related to the question; just for future purpose. In my case, I got this error message when using regex. Here is my code and the correction
text = "Hey I'm Kelly, how're you and how's it going?"
import re
When I got error:
x=re.search(r'('\w+)|(\w+'\w+)', text)
The correct code:
x=re.search(r"('\w+)|(\w+'\w+)", text)
I'm meant to use double quotes after the r instead of single quotes.