DR8
DR8

Reputation: 137

How can I return multiple values from a function?

I'm stuck with functions... I want to make a function that greets all the names I have in a list in 3 different ways: Good morning, Good afternoon and Good night.

I was able to reach the code below, but I'm not conffident that is the best way and in fact it isn't because the names in my list don't appear in the output.

My code is:

def greet(greeting, names):
    #return a greeting and then the list of names
    return (greeting)
    for name in names:
        return (f'- {name}.')

names = ['Phoebe', 'Rachel', 'Chandler']

#Say good morning to all
morning = greet('\nGood morning,', names)

#Say good afternoon to all
afternoon = greet('\nGood afternoon,', names)

#Say good night to all
night = greet('\nGood night,', names)

print (morning)
print (afternoon)
print (night)

Output:

Good morning,

Good afternoon,

Good night,

The expected output was suppose to be:

Good morning,
- Phoebe.
- Rachel.
- Chandler.

Good afternoon,
- Phoebe.
- Rachel.
- Chandler.

Good night,
- Phoebe.
- Rachel.
- Chandler.

What am I doing wrong?

Upvotes: 0

Views: 338

Answers (3)

TheMaster
TheMaster

Reputation: 50774

return can only be used executed once inside a function. Try concatenating the string before returning.

def greet(greeting, names):
    #return a greeting and then the list of students
    str = greeting
    for name in names:
        str+= (f'\n- {name}.')
    return str

names = ['Phoebe', 'Rachel', 'Chandler']

#Say good morning to all
morning = greet('\nGood morning,', names)

#Say good afternoon to all
afternoon = greet('\nGood afternoon,', names)

#Say good night to all
night = greet('\nGood night,', names)

print (morning)
print (afternoon)
print (night)

Upvotes: 2

Kovy Jacob
Kovy Jacob

Reputation: 1121

I feel like this is what you're looking for:

def greet(greeting, names):
    #return a greeting and then the list of students
    print (greeting)
    for name in names:
        print ("- ", name)

names = ['Phoebe', 'Rachel', 'Chandler']

#Say good morning to all
morning = greet('\nGood morning,', names)

#Say good afternoon to all
afternoon = greet('\nGood afternoon,', names)

#Say good night to all
night = greet('\nGood night,', names)

Upvotes: 1

Anshumaan Mishra
Anshumaan Mishra

Reputation: 1362

The return statement also acts as a function terminator. So try print(greeting) instead of return(greeting) and also inside the loop. Final code:

def greet(greeting, names):
    #return a greeting and then the list of students
    print (greeting)
    for name in names:
        print (f'- {name}.')

names = ['Phoebe', 'Rachel', 'Chandler']

#Say good morning to all
greet('\nGood morning,', names)

#Say good afternoon to all
greet('\nGood afternoon,', names)

#Say good night to all
greet('\nGood night,', names)

Upvotes: 1

Related Questions