This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 9: The PEP 8 style guide

Breaking expressions and strings

face Josiah Wang

How do you break up expressions into multiple lines?

The preferred way is to just make use of parenthesis (as well as square brackets and curly braces in later lessons). This is known as “implied line continuation”.

total = (first_variable 
         + second_variable
         - third_variable)

Also note how we followed PEP 8’s recommendation to break before operators. PEP 8 also allows you to break after the operators as long as it is consistent. We will not be enforcing this either - just be consistent!

The alternative way to break up expressions (if you cannot use implied line continuation) is to use a backslash. For example, maybe you need your favourite Rick Astley song to be in a single line. Note that this is sensitive to any spaces you include though.

>>> lyrics = "Never gonna give you up,\
...    Never gonna let you down,\
...    Never gonna run around and desert you."
>>> lyrics
'Never gonna give you up,    Never gonna let you down,    Never gonna run around and desert you.'

In this case, parenthesis might work better for better readability. Python has a feature that automatically concatenate adjacent strings.

>>> lyrics = ("Never gonna give you up, "
...           "Never gonna let you down, "
...           "Never gonna run around and desert you.")
>>> lyrics
'Never gonna give you up, Never gonna let you down, Never gonna run around and desert you.'