Usage of \ symbol in python

Hi all,

Quick one. Just came across this bit of code:

total_earned = lambda row: (row.hourly_wage * 40) + ((row.hourly_wage * 1.5) * (row.hours_worked - 40)) \

  if row.hours_worked > 40 \

  else row.hourly_wage * row.hours_worked

All makes sense except the use of \, I have not seen this before. Does this just mean that the line break is ignored? So this codeblock will be processed as if it is all one line? (so more for readability?)


Hey. \ just indicates that your code will be continued on the next line. For example, take this piece of code.

distance = 2 + \
print(distance)   #This will print out 5

On the other hand, if I were to do the same but leave out the \, I would get an error saying ‘invalid syntax’. Hope this makes some sort of sense. Here’s another page that explains it in more detail in case you want some more examples. I’m not very advanced in python so I’m not able to directly help you with that specific piece of code, but I thought I’d share what I know.


That’s great, cheers!

Coming from javascript so still getting used to the importance of lines and indents!

If you are new to Python then this is certainly not something one would expect from a learner…

total_earned = lambda row: (row.hourly_wage * 40) + \
    ((row.hourly_wage * 1.5) * (row.hours_worked - 40)) \
    if row.hours_worked > 40 \
    else row.hourly_wage * row.hours_worked

Which lesson did this code come from?

ah it was a while ago now. Im pretty sure it was one of “introduction to pandas” lessons.

It makes sense having it explained, it was just set as a solution to one of the tasks with zero explanation.

1 Like

You’ll notice that the above code is a conditional expression in a lambda expression. I’m not sure the conditional expression is even taught in the basic Python course or anywhere expressly that I can recall. It’s not uncommon for authors to throw in code patterns that haven’t been taught. Better course auditing would bring this to bear, but that is not our purview over here.


def cmp(a, b):
    return 1 if a > b else -1 if b > a else 0

This is the Python near equivalent to a JS ternary expression…

return a > b ? 1 : b > a ? -1 : 0;
print (cmp(6, 5), cmp(5, 6), cmp(6, 6))    # 1 -1 0

A lambda is an anonymous function expression nearly equivalent to a defined function except it can be returned (or assigned) in its written form. If this is new then a quick segue to the documentation and/or some articles on the subject would be well worthwhile.

The advanced courses can sometimes take it for granted that a learner has more background that they might actually have. Whenever coming across code patterns you don’t recognize, bring them up here and give attribution to the lesson where you found it. That way you don’t get in too deep before grinding to a halt.