When writing lambda functions with if/else, do we need to include backslashes?


#1

Question

In the context of this exercise, the example lambda functions, which use an if/else statement, were written using a backslash (\). Do we always need to include backslashes when writing lambda functions using if/else?

Answer

No, you do not always need to include backslashes \ when you write lambda functions with if/else statements.

In Python, the backslash character \, also called the “line continuation character”, is used to join two lines of code. When you have a backslash at the end of a code line, Python will continue reading the next line of code as though the lines are part of a single line of code.

We use backslashes for the main purpose of making the code easier to read, by decreasing the length of the code lines. In particular, lambda functions can become quite long and hard to read because they are a single line, which is why we usually apply backslashes to divide them into multiple lines.

Example

# A statement as a single line
print 1 + 3

# The same statement split into multiple lines
print \
1 + \
3

One important thing to keep in mind is that there cannot be any characters or spaces after a backslash. A backslash must be the very last character of a code line. Otherwise, an error will be thrown.