How to use return statement to return multiple lines of code?

How do I use the return statement to return multiple strings without putting the strings in a sequence?

I want to use the return statement instead of using the print statement in a scenario like this one

return "Hi!" + "Greetings!

Would that work?

1 Like

You could just separate them with a comma

def name() -> tuple[str, str, str]:
    return 'Hello', 'Hi', 'greetings!'

And to access each one

print(name()[0]) # Hello

\n in a string is replaced with a newline:

Or you can use multi-line strings:

  return """Hello
Hi
greetings!"""
4 Likes

Here’s one way:

def name():
  return 'Hello', 'Hi', 'greetings!'

Then print with either:

for string in name():
  print(string)

or:

print(*name(), sep='\n')

(\n is a newline.)

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.