Python - How to use a return statement in a for loop?

时间:2017-06-15 09:54:11

标签: python python-3.x function return

First of all I want to apologize for the bad title, but it was the best I could do. I tried to take a lot of screenshots to hopefully make this a little bit easier to understand.

So I am working on a chat-bot for discord, and right now on a feature that would work as a todo-list. I have a command to add tasks to the list, where they are stored in a dict. However my problem is returning the list in a more readable format (see pictures).

def show_todo():
    for key, value in cal.items():
        print(value[0], key)

The tasks are stored in a dict called cal. But in order for the bot to actually send the message I need to use a return statement, otherwise it'll just print it to the console and not to the actual chat (see pictures).

def show_todo():
    for key, value in cal.items():
        return(value[0], key)

Here is how I tried to fix it, but since I used return the for-loop does not work properly.

So how do I fix this? How can I use a return statement so that it would print into the chat instead of the console?

Please see the pictues for a better understanding

3 个答案:

答案 0 :(得分:6)

Using a return inside of a loop, will break it and exit the method/function even if the iteration still not finished.

For example:

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

In some cases/algorithms we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it it is an error/bad design.

Instead of that, you can use a different approach:

yielding your data:

def show_todo():
    # Create a generator
    for key, value in cal.items():
        yield value[0], key

You can call it like:

a = list(show_todo()) # or tuple(show_todo()) and you can iterate through it too.

Appending your data into a temporar list or tuple or dict or string then after the exit of your loop return your data:

def show_todo():
    my_list = []
    for key, value in cal.items():
        my_list.append([value[0], key])
    return my_list

答案 1 :(得分:4)

Use a generator syntax (excellent explanation on SO here):

def show_todo():
    for key, value in cal.items():
        yield value[0], key

for value, key in show_todo():
    print(value, key)

答案 2 :(得分:0)

您永远不能迭代返回任何东西。只需返回一个列表并对其进行迭代即可得到结果。

def show_todo():
    return [key, val for key, val in cal.items()]