How to Return Multiple Lines of Output in Python?

Estimated read time 2 min read

In Python, you can return multiple lines of output by using multi-line strings or by returning a list of strings. Here are examples of both approaches:

  1. Multi-line strings: You can use triple quotes (""" or ''') to define a multi-line string that spans across multiple lines. This allows you to return multiple lines of output as a single string. Here’s an example:
def get_output():
    output = """
    Line 1 of output
    Line 2 of output
    Line 3 of output
    """
    return output

result = get_output()
print(result)

In this example, the get_output() function returns a multi-line string with three lines of output. The output is stored in the result variable and printed.

  1. List of strings: Another approach is to return a list of strings, where each string represents a line of output. This allows for more flexibility if you need to process or modify each line individually. Here’s an example:
def get_output():
    output = [
        "Line 1 of output",
        "Line 2 of output",
        "Line 3 of output"
    ]
    return output

result = get_output()
for line in result:
    print(line)

In this example, the get_output() function returns a list of three strings, where each string represents a line of output. The lines are stored in the result variable, and then each line is printed separately in the for loop.

Both approaches have their advantages depending on the context and requirements of your code. Choose the one that best suits your needs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply