[SOLVED] Return values from a function

Issue

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?

Solution

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)

Answered By – Barmar

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.