Skip to main content
 首页 » 编程设计

python之使用 while 循环返回一个函数

2025年05月04日7itcoder

In main function:

Create a list that holds the surnames of recent USA presidents, starting with Kennedy and ending with Obama, in chronological order. use a for loop to iterate over the entire list, printing each president's name on its own line. make a slice by removing the first two presidents and the last two presidents from the list. pass the new slice as an argument to a custom function named playlist. use a while loop to display the elements in the list returned by playlist.

In playlist function:

print the size of the sliced list. Use a list function. sort the sliced list in reverse alphabetical order. return this list to main.

这就是我目前所拥有的。我不知道如何插入 while 循环。每次我这样做时,列表都会继续显示,否则就不会显示。

def main(): 
    #Create list. 
    names = ['Kennedy', 'Johnson', 'Nixon', 'Ford', 'Carter', 'Reagan', 'Bush', 'Clinton', 'Bush', 'Obama'] 
    sliced_list = names[2:8] 
 
    #Display the list. 
    print('Here are the most recent presidents of the USA') 
    for n in names: 
    print(n) 
    sliced = playlist(sliced_list) 
 
 
def playlist(sliced_list): 
    size = len(sliced_list) 
    print('The list size is now', size) 
    sliced_list.sort() 
    sliced_list.reverse() 
    return sliced_list 
 
main() 

这就是它应该如何返回。

Original list in main: 
Kennedy 
Johnson 
Nixon 
Ford 
Carter 
Reagan 
Bush 
Clinton 
Bush 
Obama 
Not in main: list size is now 6 
Back in main, list in reverse alpha order 
Reagan 
Nixon 
Ford 
Clinton 
Carter 
Bush 

请您参考如下方法:

在不修改列表的情况下使用 while 循环遍历列表元素:

i = 0 
while i < len(sliced): 
    print(sliced[i]) 
    i += 1 

如果您更喜欢 browskie 建议的改变列表的方法,我建议避免使用 try-except block ,如下所示:

while len(sliced): 
    print(sliced.pop(0))