Continuation and Organization of Code in Python

Line Continuation in Python

Sometimes, you need to split a long statement across multiple lines for readability. Python offers two main ways:

1. Implicit Line Continuation

Inside parentheses (), brackets [], or braces {}, you can split lines without any special character.

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

result = (1 + 2 + 3 +
          4 + 5 + 6)

2. Explicit Line Continuation with Backslash

Use a backslash \ at the end of the line to indicate continuation:

total = 1 + 2 + 3 + \
        4 + 5 + 6

Note: Avoid unnecessary backslashes when implicit continuation can be used.

Code Organization Best Practices

Organizing your code well makes it easier to read, maintain, and reuse.

def main():
    # Main program logic here
    print("Program started")

if __name__ == "__main__":
    main()

Additional Best Practices

Example: Organized Python Script

def add(a, b):
    """Return sum of a and b."""
    return a + b

def main():
    result = add(5, 7)
    print(f"Sum is {result}")

if __name__ == "__main__":
    main()