Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can I use "\" to write commands over two lines, but not more than two?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading