What puts \ at the end of a line in python?

I am looking at the following code snippet:

totalDistance += \ GetDistance(xCoords[i], yCoords[i], xCoords[i+1], yCoords[i+1]) 

and can’t understand what += \ means?

+7
source share
3 answers

\ at the end of the line simply indicates that it will continue on the next line, because otherwise ( totalDist += ) will cause an error ... (it is also important to note that after the slash there can be nothing ... not even spaces)

+= just adds and assigns back

 x = 1 x += 1 # x is now 2 (same as x = x + 1) 
+17
source

\ returns a line immediately after it (there should be no character between \ and implicit \n ).

There are also a few other exceptions; newlines are ignored if they are enclosed in match pairs:

  • []
  • ()
  • {}

In other words, the following equivalents:

 a= [1,2,3] a = [1, 2, 3] 
+7
source

The combination \ followed by a new line means the continuation of the line. You can think of \ as an exit from a new line, so that it does not have the usual "end of line" value.

In Python, you can often arrange the code so that \ not necessary, for example.

 totalDistance += GetDistance( xCoords[i], yCoords[i], xCoords[i+1], yCoords[i+1]) 

here the newlines do not end because they are inside ()

+4
source

All Articles