List保留数据但不保留字符串?



我正在做一些Python编程书中的练习,我们应该操作一个列表。我决定为这个任务定义一些函数,我的第一个函数如下:

guest_list = []
guest_list_text = ""
def invite_guests():
user_choice = input("Would you like to add a guest to the guest list? ").lower()
while user_choice == "yes":
"""Initially I used an if/else statement in this while loop, but I realized I didn't need
them for this task."""
guest_list.append(input("Who would you like to invite? ").title())
guest_list_text = ", ".join(guest_list)
print("Great! I'll add them to the list!")
print(f"So far you've invited {guest_list_text} to the party.")
"""We're gonna leave this as is for now; what matters most right now is getting in my reps, 
not perfect code. We learned how to use join here. Create an empty string, then assign
the list you want to join to it with join--what's inside the quotes will join the items."""
user_choice = input("Would you like to add another guest to the list? ").lower()
print(f"I've sent the following message to {guest_list_text}: ntHello! I'm throwing a dinner party, would you like to come?")
return guest_list_text

我有一个列表"guest_list"和字符串&;guest_list_text&;,我想你会称它们为全局变量,因为它们在任何函数之外?好吧,后来我尝试在一个新函数中使用guest_list_text,在该函数中使用或不使用它作为参数。我试图打印一条消息:

print(f"Sending an update to {guest_list_text}: Good news everyone! We've found a bigger table!n" 
"That means I'll be inviting more people!")

输出是:" I've sent the message to:"为了解决这个问题,我必须在新函数中输入:

guest_list_text = ", ".join(guest_list)

所以这告诉我,由于某种原因,列表保留了第一个函数的数据,但字符串没有。有人能给我解释一下吗?

Python理解guest_list是全局的,因为您在函数(guest_list.append(...))中使用它而没有局部声明,但对于guest_list_text是不同的,因为您在guest_list_text = ", ".join(guest_list)中为其分配值,但Python将其理解为局部变量声明,用于告诉Python您想将guest_list_text视为全局变量,您可以使用global guest_list_text,像这样:

guest_list = []
guest_list_text = ""
def invite_guests():
global guest_list_text
user_choice = input("Would you like to add a guest to the guest list? ").lower()
while user_choice == "yes":
"""Initially I used an if/else statement in this while loop, but I realized I didn't need
them for this task."""
guest_list.append(input("Who would you like to invite? ").title())
guest_list_text = ", ".join(guest_list)
print("Great! I'll add them to the list!")
print(f"So far you've invited {guest_list_text} to the party.")
"""We're gonna leave this as is for now; what matters most right now is getting in my reps, 
not perfect code. We learned how to use join here. Create an empty string, then assign
the list you want to join to it with join--what's inside the quotes will join the items."""
user_choice = input("Would you like to add another guest to the list? ").lower()
print(f"I've sent the following message to {guest_list_text}: ntHello! I'm throwing a dinner party, would you like to come?")
return guest_list_text

正如Rodrigo Llanes的回答所述,您的代码失败是因为您在invite_guests()函数的局部范围内操作全局变量。在函数内将该变量声明为global将如您所期望的那样解决问题。然而,在许多情况下,全局变量是一种不好的做法,因为它们产生了一个隐式声明:您更改了变量的值,而没有实际声明这样做的意图。例如,反对你在声明guest_list = []时所做的事情。这可能会导致您的程序产生意想不到的输出,这可能很难调试。

这里有一个有趣的讨论。

所以,我想提出另一种方法:

guest_list = []
guest_list_text = "There're no guests in the list yet!"
def invite_guests(guest_list):
guest_list_text = ""
user_choice = input("Would you like to add a guest to the guest list? ").lower()

while user_choice == "yes":
guest_list.append(input("Who would you like to invite? ").title())
guest_list_text = ", ".join(guest_list)
print("Great! I'll add them to the list!")
print(f"So far you've invited {guest_list_text} to the party.")
user_choice = input("Would you like to add another guest to the list? ").lower()
print(f"I've sent the following message to {guest_list_text}: ntHello! I'm throwing a dinner party, would you like to come?")
return guest_list, guest_list_text

然后你可以像这样调用这个函数:

guest_list, guest_list_text = invite_guests(guest_list)

现在您可以对多个来宾列表使用相同的函数。注意,列表和列表文本的调用方式不一定与函数内部调用方式相同。您可以这样做,例如friends_list, friends_list_text = invite_guests(friends_list)

但你也有一行明确地说,"嘿,python,现在创建一个客人列表!"这将使事情变得更容易,如果有些事情不像预期的那样工作。

最新更新