这更多的是一个帮助我学习Python时理解的问题。我正在练习一本练习册,并提出了以下挑战:
从练习 8-9 中的程序副本开始。 编写一个名为 send_messages() 的函数,用于打印每条短信并 在打印每条消息时将其移动到一个名为“sent_messages”的新列表。后 调用该函数,打印两个列表以确保消息是 移动正确。
我最初编写的代码使用了“for”循环,它没有迭代所有消息:
messaging = ['Hello world!', 'Keep it coming!', "Don't give up!", "I'm getting hungry!"] # list of messages to send
sent_messages=[] # list of sent messages
def show_messages(messages): #define the name of a list in function
**for message in messages: #while loop to keep running until list has been gone through
current_mess = messages.pop() #remove latest message
print(current_mess) # print latest message
sent_messages.append(current_mess) # add latest message to sent_messages
show_messages(messaging[:]) #create a copy of the messaging list so original isn't touched by using a slice
print(messaging)
print(sent_messages)`
其输出如下:
我饿了! 不要放弃! [‘你好世界!’、‘继续加油!’、‘不要放弃!’、‘我饿了!’] [“我饿了!”、“不要放弃!”]
但是,当我将函数更改为具有“while”循环时,它工作正常:
messaging = ['Hello world!', 'Keep it coming!', "Don't give up!", "I'm getting hungry!"] # list of messages to send
sent_messages=[] # list of sent messages
def show_messages(messages): #define the name of a list in function
while messages: #while loop to keep running until list has been gone through
current_mess = messages.pop() #remove latest message
print(current_mess) # print latest message
sent_messages.append(current_mess) # add latest message to sent_messages
show_messages(messaging[:]) #create a copy of the messaging list so original isn't touched by using a slice
print(messaging)
print(sent_messages)
输出:
我饿了! 不要放弃! 继续吧! 你好世界! [‘你好世界!’、‘继续加油!’、‘不要放弃!’、‘我饿了!’] [“我饿了!”、“不要放弃!”、“继续努力!”、“世界你好!”]
我主要好奇这两个版本的代码在工作中到底发生了什么,而一个版本则不然,这可能会提高我对循环的理解。
For 循环将一直运行,直到您迭代完要迭代的事物中的所有内容为止。 While 循环运行直到条件变为假。在您的情况下,条件变为假,因为对象为空,这是大多数编程语言的约定。这是为了给你正确的想法而进行的一点简化