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

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.

8 Likes

I’m slightly confused by the if and else used in this exercise. In an earlier exercise these were used but the true part of the if was written before the if but the example didn’t follow this layout, see below :

def myfunction(x):
    if x > 40:
        return 40 + (x - 40) * 1.50
    else:
        return x

my expectation was that it should have been written like this in order for it to be successfully executed :

def myfunction(x):
        return 40 + (x - 40) * 1.50
    if x > 40:

    else:
        return x

how does python identify the true part within this code, the false part I understand is clearly stated when entering else ?

Hello, @script0351949381. Not sure I understand your question. The first example is a ‘textbook’ if ... else block of code:

The second example will throw an error because there is no indented code following the if x > 40:.
We could modify the code to run without error, but it would not provide the same result as the first example.

You may have been referring to this type of expression:

def myfunction(x):
    return 40 + (x - 40) * 1.50 if x > 40 else x
    #the expression preceding x is returned if x > 40 otherwise x is returned

The above is the Python version of a ternary operator or conditional expression. The placement of the expressions is how Python knows what is what.

Thank you. I think what is confusing me is in your last example the true part of the if is at the start of the function (return 40 + (x - 40) * 1.50 ) however within my first example the true part of the function is post the if x > 40: i guess this means that the placement of the true part isn’t integral? apologies if I haven’t explained myself well.

The ternary operator is like shorthand for the standard if ... else. Using the ternary operator limits us somewhat. We can’t execute multiple lines of code if True or if False. We just assign a value either to a variable or as an argument to another function or method like print() or return. The placement of the various parts depends on which method you are using:

#simple variable assignment:

#ternary
my_variable = value_if_true if boolean_expression else value_if_false

#if ... else
if boolean_expression:
    my_variable = value_if_true
else:
    my_variable = value_if_false
1 Like

In this exercise we need to write a lambda function with if/else statement that does an age check for over 13. The solution code is this:

import codecademylib

mylambda = lambda x: ‘Welcome to BattleCity!’
if x >= 13
else ‘You must be over 13’

My question is this, why do we not have to include print? As in print(“Welcome to BattleCity!”) & print(“You must be over 13”)

Note the specific text of the exercise asks for it to RETURN the text strings, not print it. We assume that printing it to the scrren could happen later in the code.

You are managing the webpage of a somewhat violent video game and you want to check that each user’s age is 13 or greater when they visit the site.

Write a lambda function that takes an inputted age and either returns Welcome to BattleCity! if the user is 13 or older or You must be over 13 if they are younger than 13. Your lambda function should be called mylambda .

Lambda functions implicitly return result from out function. Generally when you’re using functions you want to return results rather than just print them to the console.

Returning results from functions allows us to use the result value for further computation, but if we print if out we can’t use it for further computation. Example. Imagine you’re in physics class and you want to calculate and get results in S.I units. Let’s say we are calculating Speed. SI unit of distance is metres, time is seconds and speed is m/s. Now imagine we were given distance in kilometres and time in hours. We’ll need to convert it first

def time_in_seconds(time):
return time * 60 * 60

def distance_in_metres(dist):
return dist * 1000

now we can use the return values for further computation. Let’s say distance is 5 kilometres and time is 2 hours
we now have:

speed = distance_in_metres(5) / time_in_seconds(2)

print(speed)
#0.6944

If we had used print inside our function, the result of our conversion would have just been outputted to the console and we wouldn’t have been able to use it in further calculations