Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return values from a function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading