8

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
  • 22,540
  • 20
  • 65
  • 127
  • 1
    i think \ will work.. – iamklaus Dec 04 '18 at 14:50
  • 2
    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

20

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
  • 59,676
  • 15
  • 85
  • 126
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
  • 80,714
  • 11
  • 64
  • 111