12

I have a long expression, its' not fitting in my screen, I want to write in several lines.

new_matrix[row][element] =  old_matrix[top_i][top_j]+old_matrix[index_i][element]+old_matrix[row][index_j]+old_matrix[row][index_j]

Python gives me 'indent' error if I just break line. Is there way to 'fit' long expression in screen?

ERJAN
  • 23,696
  • 23
  • 72
  • 146
  • 1
    i think \ will work.. – iamklaus Dec 04 '18 at 14:50
  • 3
    See [PEP8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator) advice. If you put the expression in `()` then you can break on the operators, e.g. `+` – T Burgis Dec 04 '18 at 14:50

3 Answers3

30

I hate backslashes, so I prefer to enclose the right hand side in parens, and break/indent on the top-level operators:

new_matrix[row][element] = (old_matrix[top_i][top_j]
                            + old_matrix[index_i][element]
                            + old_matrix[row][index_j]
                            + old_matrix[row][index_j])
PaulMcG
  • 62,419
  • 16
  • 94
  • 130
4

You can break expressions into multiple lines by ending each line with \ to indicate the expression will continue on the next line.

Example:

new_matrix[row][element] =  old_matrix[top_i][top_j]+ \
    old_matrix[index_i][element]+old_matrix[row][index_j]+ \
    old_matrix[row][index_j]
Immijimmi
  • 111
  • 3
2

Yes, use \:

new_matrix[row][element] =  old_matrix[top_i][top_j]+old_matrix[index_i]\ 
                            [element]+old_matrix[row][index_j]+old_matrix[row][index_j]
yatu
  • 86,083
  • 12
  • 84
  • 139