Breaking lines in python

How to Break Long Lines in Python

Python supports implicit line continuation. This means you can break long lines of code.

For example, instead of this:

math_students = ["Alice", "Bob", "Charlie", "David", "Emmanuel"]

You can write it like this:

math_students = [ "Alice", "Bob", "Charlie", "David", "Emmanuel" ]

As a matter of fact, you should limit all lines of code to a maximum of 79 characters.

Today, you are going to learn when and how to break long lines in Python.

Breaking Long Lines of Code in Python

Breaking lines increases the total number of lines of code. But at the same, it can drastically improve the readability of your code.

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.

For example, here is a long print() function call is broken into multiple lines in a couple of ways:

print("Alice", "Bob", "Charlie", "David", "Emmanuel", "Farao", "Gabriel", "Hilbert", "Isaac") print( "Alice", "Bob", "Charlie", "David", "Emmanuel", "Farao", "Gabriel", "Hilbert", "Isaac" ) print( "Alice", "Bob", "Charlie", "David", "Emmanuel", "Farao", "Gabriel", "Hilbert", "Isaac" )

There are many ways you can break long lines in Python. You may want to check the official style guide that explains best practices more thoroughly.

Before jumping into examples, notice that there is a way to automatize the line-breaking process.

How to Auto-Break Long Lines of Code in Python

Popular code editors allow you install plugins that enforce code style guidelines.

A cool feature of these plugins is you can usually auto-format code. In other words, the plugin automatically takes care no line exceeds the 79 character “limit”.

For example, in VSCode it is possible to automatically format code on save.

Next up, let’s see some examples when you may want to split expressions into multiple lines.

How to Break a String into Multiple Lines

To break a string to multiple lines, wrap each string in the new line inbetween a pair of double quotation marks.

Читайте также:  H rem ru chiptuning hyundai html

For instance, you can do this:

print( "This happens to be" " so long string that" " it may be a better idea" " to break the line not to" " extend it further to the right" )

But you cannot do this:

print( "This happens to be so long string that it may be a better idea to break the line not to extend it further to the right" )

Break a Function Arguments into Multiple Lines

If your function takes a number of arguments that extends line of code far to the right, feel free to break the expression into multiple lines.

For example, instead of doing this:

def example_function(first_number, second_number, third_number, fourth_number, fifth_number): pass
def example_function( first_number, second_number, third_number, fourth_number, fifth_number ): pass

Break a List into Multiple Lines

For example, let’s create a 3×3 matrix using a list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

This is fine, but as you may know, a matrix is written in a table format. This makes it look more like a table of values.

To follow this convention in Python, you can split the matrix (the list of lists) into multiple lines:

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

Break a Dictionary into Multiple Lines

Just like breaking a list declaration into multiple lines, you can do it with a dictionary.

For instance, instead of a long expression like this:

Let’s split the dictionary into a bunch of lines to make it more understandable:

Break Mathematical Operations into Multiple Lines

To split a chain of binary operations, break the line before the operator. This makes the code more readable as the binary operators are not all over the place.

For example, instead of doing this:

income = gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest
income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest)

This example is directly from the PEP-0008 style guide.

Break Comparisons into Multiple Lines

Like any other expression, comparisons can also take some space. To avoid too long chains of comparisons, you can break the line.

if (is_rainy == True and is_hot == True and is_sunny == True and is_night == True): print("How is that possible. ")

Conclusion

Python’s implicit continuation makes it possible to break long expressions into multi-line expressions. This is useful for code readability.

To break an expression into multiple lines, wrap the expression around a set of parenthesis and break it down as you want.

If the expression is already in a set of parenthesis, square brackets, or curly braces, you can split it to multiple lines. This is true for example for lists, tuples, and dictionaries.

Читайте также:  Multiprocessing dummy python 3

Thanks for reading. I hope you like it.

Источник

Breaking long lines in Python

In some of the programs discussed in the book including the sample solutions, you will see statements like:

print('Area: , Estimated (): '. format(area_of_circle, points, estimate(radius, points)))

This is really the following single statement:

print('Area: , Estimated (): '.format(area_of_circle, points, estimate(radius, points)))

The first code snippet above is an example of breaking a long line into two (or more) lines so that we don’t end up with really long lines in our code. How long should a line be when you should think about breaking it? If your statement’s length is more than 80 characters, you should think about breaking it up.

In the book, we often had to do so because of layout reasons even though the statement may not have exceeded 80 characters, and in your projects you will want to do it so that your statements are easier to read and on the average all lines have a similar length. This is formalized (among other things) in PEP 8.

Note that the examples below will for illustrative purposes break lines waaaaay less than 80 characters.

How do you break?

When not calling function

When you are not calling a function, you essentially have two choices:

Use paranthesis

This is exactly how we break the long statement in the example we started this article with. For the moment ignore the call to print() and assume that the statement is:

s = 'Area: , Estimated (): '.format(area_of_circle, points, estimate(radius, points))

This essentially just creates the string s. If we were to split this statement over multiple lines, we would do the following:

s = ('Area: , Estimated (): ' .format(area_of_circle, points, estimate(radius, points)))

Note the extra beginning and the ending parenthesis.

s1 = x + x**2/2 + x**3/3 + x**4/4 + x**5/5 + x**6/6 + x**7/7 + x**8/8

Here is how we can use split the above statment into multiple lines using parentheses:

s3 = (x + x**2/2 + x**3/3 + x**4/4 + x**5/5 + x**6/6 + x**7/7 + x**8/8)

Use the line continuation operator

The line continuation operator, \ can be used to split long statements over multiple lines. Here is how we could split the above statement using \ instead:

s3 = x + x**2/2 + x**3/3 \ + x**4/4 + x**5/5 \ + x**6/6 + x**7/7 \ + x**8/8

At the end of every line (except the last), we just add a \ indicating that the next line is also a part of the same statement.

Breaking up those long if statements

Читайте также:  Get all private fields java reflection

Often I have to break long if statements and is in fact one of the most common cases I face at work where I have to break the statement into multiple lines. Here is an example using both the approaches above:

# Using parenthesis if (cond1 and cond2 and cond3 and cond4): # True block else: # False block # Using line continuation operator if cond1 and cond2 and cond3 \ and cond4: # True block else: # False block

When calling functions

By default, when calling functions you can just press enter and without doing anything more keep writing your statement over multiple lines. For example:

Hence, we could have broken the first example we saw as:

print('Area: , Estimated (): '.format(area_of_circle, points, estimate(radius, points)))

When calling format() we put the arguments over separate lines.

Learning more about Python coding style

If you liked reading this article, you may also find it worth your time going over the Python style guide. You may even find instances where I have not followed a guideline when writing the programs in the book. If you find one, let me know.

Getting in touch

Stay updated or get in touch:

You can contact me directly via:

social

Источник

How to print a line break in Python

How to print a line break in Python

When you’re working with strings, knowing how to create a line break is very useful.

A line break allows you to define when a section of text should be broken into multiple lines.

Rather than printing text multiple times, each on a different line, you can define a single text string that contains line breaks.

In this post, we’ll look at how to use line breaks in Python.

Using line breaks in Python

The easiest way to use line breaks in Python is to use the \n character. This character indicates that the text that follows after it will be on a new line.

Simply include the \n character in your string when you want to break the text into multiple lines.

Here’s an example of a 3-line string:

Another useful way to use line breaks is when you’re in a loop.

Conclusion

In this post, we learned about how to use line breaks in Python.

To create a line break, simply include the \n character in your string.

Thanks for reading and happy coding!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Оцените статью