我怎样才能 return 一个函数的多个值?

How can I return multiple values from a function?

我被函数困住了... 我想创建一个函数,以 3 种不同的方式问候列表中的所有名字:早上好、下午好和晚安。

我能够找到下面的代码,但我不确定这是最好的方法,事实上这不是因为我列表中的名字没有出现在输出中。

我的代码是:

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)

输出:

Good morning,

Good afternoon,

Good night,

预期的输出应该是:

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

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

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

我做错了什么?

return 语句也充当函数终止符。所以尝试 print(greeting) 而不是 return(greeting) 并且也在循环内。最终代码:

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)

return 只能 used 在函数内执行一次。返回前尝试连接字符串。

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)

我觉得这就是您要找的:

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)