How to write long arithmetic expressions in several lines in python? [duplicate]
Asked Answered
Y

3

13

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?

Yeaton answered 4/12, 2018 at 14:49 Comment(2)
i think \ will work..Lingo
See PEP8 advice. If you put the expression in () then you can break on the operators, e.g. +Wira
C
32

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])

or (I think this is how black does it):

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]
)
Crispen answered 4/12, 2018 at 14:55 Comment(1)
this seems the most legit.. i hate slash linesYeaton
S
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]
Sepsis answered 4/12, 2018 at 14:52 Comment(2)
It's not good to continue a line with the same indentation as the start segment.Cochise
Fair point, edited.Sepsis
S
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]
Syngamy answered 4/12, 2018 at 14:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.