Python Forum

Full Version: print function help percentage and slash (multiple variables)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
What is the function of adding a back slash in the following code after the percentage operator? I am testing it without the slash and it gives the same result.
Please note that I know I am not currently using the best practice for string formatting (format function method) in this example.

def distance(a,b):
    """ a and b are tuples. Finds the distance between them """
    return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5
p1=(10,10)
p2=(10,20)
p3=(20,20)

print("The distance between %s and %s is %0.1f."%\
(str(p1),str(p2),distance(p1,p2)))
print("The distance between %s and %s is %0.1f."%\
(str(p1),str(p3),distance(p1,p3)))
The author of this code wanted to split the print across multiple lines. Most python statements need to be on a single line. But there are cases where it can continue on to another line.

One method of splitting a line is to use a terminal backslash. If I try to put a return within a regular statement without the backslash, it will complain
>>> a = 2 +
  File "<stdin>", line 1
    a = 2 +
          ^
SyntaxError: invalid syntax
>>> a = 2 + \
... 3
>>> a
5
Because this works and because this method is how many other languages like C allow for line splitting, folks may get in the habit of always using the backslash when splitting statements across lines. But there are some other situations where line splitting is allowed without backslashes: triple quotes, and parenthesis/bracket/braces.

Your code above is within parenthesis, so even without the backslash, the return does not terminate the statement.

>>> a = (2 +
... 3)
>>> a = {2 +
... 3}
>>> a = [2,
... 3]
>>> a = """ A two and
... a three """
Hi. Thanks bowlfred. That was super-helpful. As I tried to search for an explanation online and this answered it.
Can I have one question. What did you mean by return in

"the return does not terminate the statement"?
"return" as in carriage return. When you hit return to go to the next line, it terminates the statement unless you are inside parentheses/brackets/braces, you are in a triple-quote, or the return is escaped with a preceding backslash.