Home > Software design >  Return values from a function
Return values from a function

Time:03-06

def greet():
    for name in names:
        return (f'Hello, {name.title()}!')

names = ['ron', 'tyler', 'dani']

greets = greet()
print (greets)

Why this code isn't returning all the names?

The expected output should be:

Hello, Ron!
Hello, Tyler!
Hello, Dani!

But I'm getting only:

Hello, Ron!

When I use print instead of return within the function I am able to get all the names, but with the return I can't. Some help please?

CodePudding user response:

return ends the function. Since you do that inside the loop, the loop stops after the first iteration.

You need to collect all the strings you're creating, join them together, and return that.

def greet():
    return '\n'.join(f'Hello, {name.title()}!' for name in names)
  • Related