Search code examples
pythonindentationpep8

IndentationError on breaking a line with binary operators as per the PEP8 guidelines


I'm trying to indent the following line in Python as per the PEP8 guidelines:

temperature_rate = (temperature_values[-1] - temperature_values[0])
                   / (len(temperature_values) * MONITOR_RATE)

but I get an IndentationError at this line that states "unexpected indent":

    / (len(temperature_values) * MONITOR_RATE)
    ^
IndentationError: unexpected indent

I've tried indenting the second line in multiple ways, but they all lead to the same IndentationError. Can someone help me in understanding why I'm getting this error here?


Solution

  • There are two ways to break up long expressions, either use explicit line-continuation character, \:

    temperature_rate = (temperature_values[-1] - temperature_values[0]) \
                       / (len(temperature_values) * MONITOR_RATE)
    

    Or, the preferred way, use parenthesis:

    temperature_rate = ((temperature_values[-1] - temperature_values[0])
                        / (len(temperature_values) * MONITOR_RATE))
    

    Note, this works with any bracketed expression, which is why you could write a list-literal like:

    my_list = ['a',
               'b',
               'c']