Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does placing \ at the end of a line do in python?

Tags:

python

I'm looking at the following piece of code:

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

and can't understand what += \ means?

like image 572
paul schlacter Avatar asked Sep 26 '12 23:09

paul schlacter


People also ask

How do you end a line of code in Python?

To break a line in Python, use the parentheses or explicit backslash(/). Using parentheses, you can write over multiple lines. The preferred way of wrapping long lines is using Python's implied line continuation inside parentheses, brackets, and braces.

What does end stand for in Python?

The end parameter in the print function is used to add any string. At the end of the output of the print statement in python.

How do you continue on the next line in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line.

How do you go down a line in Python without executing the program?

Use the Ctrl - J key sequence instead of the Enter key to get a plain newline plus indentation without having IDLE start interpreting your code.


3 Answers

\ at the end of a line just indicates it will be continued on the next line as otherwise that (totalDist +=) would raise an error... (also important to note that there can be nothing after the slash ... not even whitespace)

+= just adds and assigns back

x = 1
x += 1 # x is now 2  (same as  x = x + 1)
like image 91
Joran Beasley Avatar answered Oct 03 '22 04:10

Joran Beasley


The \ escapes the line return immediately following it (there should not be any character between the \ and the implicit \n).

There are also a few other exceptions; new lines are ignored when enclosed in the matching pairs of the following:

  • []
  • ()
  • {}

In other words, the following are equivalent:

a= [1,2,3]
a = [1,
     2,
     3]
like image 22
Alexander Chen Avatar answered Oct 03 '22 02:10

Alexander Chen


The combination \ followed by newline means line continuation. You can think of the \ as escaping the newline, so that it doesn't have it's usual meaning of "line ending".

In Python, you can often arrange the code so that \ is unnecessary, eg.

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

here, the newlines don't end the line because they are inside the ()

like image 45
John La Rooy Avatar answered Oct 03 '22 02:10

John La Rooy