Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 370
ERJAN Avatar asked Dec 04 '18 14:12

ERJAN


People also ask

How do you break a long statement into multiple lines in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line.

How do you write long expressions in Python?

Using Python's inferred line continuation within parentheses, brackets, and braces is the recommended method of wrapping lengthy lines. You can put an extra pair of parentheses around an expression if required.

How do you write multiple line codes in Python?

Unlike other programming languages such as JavaScript, Java, and C++ which use /*... */ for multi-line comments, there's no built-in mechanism for multi-line comments in Python. To comment out multiple lines in Python, you can prepend each line with a hash ( # ).

How do I fix the line is too long in Python?

If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.


3 Answers

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])
like image 162
PaulMcG Avatar answered Oct 18 '22 04:10

PaulMcG


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]
like image 41
Immijimmi Avatar answered Oct 18 '22 03:10

Immijimmi


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]
like image 31
yatu Avatar answered Oct 18 '22 03:10

yatu