Need to return a list of messages

As a result, I need my program to return a list of texts in the following format: username: message So I’m using a for-loop to go through all of the users and messages and combine them into a single message. When I use the built-in function return, but, it only returns the first user and message. However, if I print them, it returns all of the users and messages.

Code:

def view_chats(self):
        try:
            z = db["messages"]["total"][-30:]
            for x in range(len(z)):
                var = f"{z[x]['username']}: {z[x]['message']}"
                # print(var)
                return var

        except:
            return "Failed to fetch last 30 messages."

It should return (it will return this if I use the print func)

beliefs: test
beliefs: test2
beliefs: test3
beliefs: hi
beliefs: hi
beliefs: ok
beliefs: ok
beliefs: ok
beliefs: hi

but instead it returns (using return func)
beliefs: test

Use yield instead

1 Like

Thank you, this solved my issue :).

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.