Home > Blockchain >  How can I return multiple values from a function?
How can I return multiple values from a function?

Time:02-20

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 above, 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 students
    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 supposed to be:

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

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

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

What am I doing wrong?

CodePudding user response:

return can only be used 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)

CodePudding user response:

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)

CodePudding user response:

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)
  • Related