How to Write Continue On Next Line in Python

Here are 3 ways to write continue on the next line in Python:

  1. Using a Backslash(\)
  2. Using Parentheses, Brackets, or Braces
  3. Implicit Line Continuation Inside String

Method 1: Using a Backslash (\)

The backslash is used as a line continuation character. When you place a backslash at the end of a line, it suggests that the line should continue on the next line.

Visual RepresentationPython Write Continue On Next Line using a Backslash(\)

Example

# Example of line continuation
total = 1 + 2 + 3 + 4 + 5 + \
        6 + 7 + 8 + 9 + 10

print(total) 

Output

55

Method 2: Using Parentheses, Brackets, or Braces

You can also continue a line onto the next one by enclosing your expression in parentheses (), brackets [], or braces {}.

This is a more Pythonic way and is often used for long function calls, lists, tuples, dictionaries, or sets.

Visual RepresentationUsing Parentheses()

Example

total = (1 + 2 + 3 + 4 + 5 +
 6 + 7 + 8 + 9 + 10)

print(total)

new_list = [
 1, 2, 3,
 4, 5, 6,
]
print(new_list)

new_dict = {1: 'A',
 2: 'B',
 3: 'C'}
print(new_dict)

Output

55
[1, 2, 3, 4, 5, 6]
{1: 'A', 2: 'B', 3: 'C'}

Method 3: Implicit Line Continuation Inside String

For strings, you can use triple single quotes (”’) or triple double quotes (“””) triple quotes to continue over multiple lines.

Visual Representation

Implicit Line Continuation Inside String

Example

multiline_string = '''This is a string that
continues over
multiple lines'''

print(multiline_string)

Output

This is a string that
continues over
multiple lines

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.