Just like C, you can break a long line into multiple short lines. But in Python, if I do this, there will be an indent error... Is it possible?
Breaking Long Lines of Code in Python It is recommended not to have lines of code longer than 79 characters. Python supports implicit line continuation. This means any expression inside the parenthesis, square brackets, or curly braces can be broken into multiple lines.
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. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.
To break a line in Python, use the parentheses or explicit backslash(/). Using parentheses, you can write over multiple lines. The preferred way of wrapping long lines is using Python's implied line continuation inside parentheses, brackets, and braces.
To break a single statement into multiple linesUse the line-continuation character, which is an underscore ( _ ), at the point at which you want the line to break.
From PEP 8 - Style Guide for Python Code:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.
Example of implicit line continuation:
a = some_function( '1' + '2' + '3' - '4')
On the topic of line breaks around a binary operator, it goes on to say:
For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.
In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.
Example of explicit line continuation:
a = '1' \ + '2' \ + '3' \ - '4'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With