return即使循环尚未完成,使用循环的内部也会破坏循环并退出函数。
例如:
def num(): # Here there will be only one iteration # For number == 1 => 1 % 2 = 1 # So, break the loop and return the number for number in range(1, 10): if number % 2: return number>>> num()1
在某些情况下,如果满足某些条件,我们需要打破循环。但是,在您当前的代码中,在完成循环之前先中断循环是无意的。
除此之外,您可以使用其他方法:
产生您的数据
def show_todo(): # Create a generator for key, value in cal.items(): yield value[0], key
您可以这样称呼它:
a = list(show_todo()) # or tuple(show_todo())
或者您可以遍历它:
for v, k in show_todo(): ...
将数据放入列表或其他容器
将数据追加到列表中,然后在循环结束后返回:
def show_todo(): my_list = [] for key, value in cal.items(): my_list.append((value[0], key)) return my_list
或使用列表理解:
def show_todo(): return [(value[0], key) for key, value in cal.items()]



