1
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?

DR8
  • 127
  • 5

2 Answers2

6

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

An alternative approach would be to use a generator function:

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

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

for greeting in greet(names):
    print(greeting)
Richard Neumann
  • 2,986
  • 2
  • 25
  • 50