以下是生成问候语消息的简单脚本:
def greeting(event, person):
print("Happy " + event + ", dear " + person + ".")
event = "Birthday"
person = "Emily"
greeting(event, person) # Happy Birtday, dear Emily.
event = "New Year"
person = "Mark"
greeting(event, person) # Happy New Year, dear Mark.
有没有办法获得相同的结果,但只调用greeting
函数一次?
答案 0 :(得分:2)
您可以将其置于循环中以处理名称和事件列表。我建议保持内部功能相同,并从外部发射一系列数据。根据您的应用,里程可能会有所不同。
def greeting(event, person):
print("Happy " + event + ", dear " + person + ".")
event_list = [("Birthday", "Emily"),
("New Year", "Mark")]
for event, person in event_list:
greeting(event, person)
答案 1 :(得分:1)
如果你只想让函数循环输入,这应该可以工作:
def greeting(messages):
for event, person in messages:
print("Happy " + event + ", dear " + person + ".")
greeting([('Birthday', 'Emily'), ('New Year', 'Mark')])
答案 2 :(得分:1)
如果您可以修改问候语:
dh-make-golang
答案 3 :(得分:1)
其他用户提到的任何一个选项都可以使用。这取决于你是想把循环放在函数中还是放在函数之外:
def greeting(event, person):
print("Happy " + event + ", dear " + person + ".")
for event, person in [("Birthday", "Emily"),
("New Year", "Mark")]:
greeting(event, person)