I’m a beginner learning Python, and I am wondering why
q = 1 + \
2
executes correctly and creates the variable q and assigns it the value 3 over two lines, but
xv\
a\
1\
= 1 + \
2
fails to execute, creating the variable xva1 and assigning it the value 3 over 5 lines as my book (A Student’s Guide to Python for Physical Modeling) states it should. I’ve tried variations of the spacing before and after the \ to no avail, since I discovered online Python is very sensitive to it.
Any help explaining why the second command fails would be much appreciated! Thanks!
>Solution :
Writing commands over more than two lines is perfectly doable.
x\
=\
1\
+\
1
works fine. The issue isn’t the number of lines; the issue is tokenization. Python tokenizes your code long before it tries to parse it, and a backslash-newline sequence is treated as whitespace. So consider your example
xv\
a\
1\
= 1 + \
2
You want it to be seen as
xva1 = 1 + 2
But in reality, the backslash-newlines get treated as whitespace, so it gets seen as
xv a 1 = 1 + 2
which is, needless to say, not valid Python syntax.