简体   繁体   中英

Return statement prints first iteration while Print outputs all iterations - Python

I'm banging my head against the wall on this:

I tested the following section of code using the print statement, it outputs all iterations as expected. However when I use return in the actual program (interacting with flask to post to a web page) it only outputs the first iteration.

This:

# Setting up cursor so we can parse results. 
cur = db.cursor()

cur.execute("SELECT user from users")
user_table = cur.fetchall()

for u in user_table:
    cur.execute("SELECT date from mood WHERE user='{}'".format(u[0]))
    user_dates = cur.fetchall()
    n = (len(user_dates) - 1) # Using this to call indexes later so need to throw away last number
    u_streak = 1
    dte_list = [ ]
    t = timedelta(days=1)
    u_streak = 1
    streak_list = [ ]
    streak_dict = {}
    sm_list = [ ]
    for dte in user_dates:
        dte_list.append(dte[0])
        dte_list = sorted(dte_list)
    for i in range(n):
        if (dte_list[i] + t) == dte_list[(i + 1)]:
            u_streak += 1
        else:
            streak_list.append(u_streak)
            u_streak = 1

    print u[0], streak_list

outputs:

codestardust [1, 1, 3]
pippen [2, 2, 5, 4]
samwise [4, 1, 1, 1]

While this :

@app.route('/mood',methods=['GET', 'POST'])
def mood():
    if request.method == 'POST':
        user = session['username']
        mymood = request.form['mymood']
        d = datetime.today().strftime('%Y-%m-%d')

        # Confirm user is logged in
        if user and mymood:
            cur.execute("INSERT INTO mood SET mood ='{}', date = '{}', user='{}'"\
            .format(mymood,d,user) )

           # Begin streak calculation
            t = timedelta(days=1)

            cur.execute("SELECT user from users")
            user_table = cur.fetchall()


            for u in user_table:
                cur.execute("SELECT date from mood WHERE user='{}'".format(u[0]))
                user_dates = cur.fetchall()
                n = (len(user_dates) - 1) # Using this to call indexes later so need to throw away last number
                u_streak = 1
                dte_list = [ ]
                u_streak = 1
                streak_list = [ ]
                streak_dict = {}
                sm_list = [ ]
                for dte in user_dates:
                    dte_list.append(dte[0])
                    dte_list = sorted(dte_list)
                for i in range(n):
                    if (dte_list[i] + t) == dte_list[(i + 1)]:
                        u_streak += 1
                    else:
                        streak_list.append(u_streak)
                        u_streak = 1

                return jsonify([u[0], streak_list])

outputs this:

["codestardust", [1, 1, 3, 4]]

I've included the entire function from the actual program to provide nesting context, in case this is a mistake with my understanding of if statements. Sorry if it is too verbose.

I see a bunch of down voted tickets like this one and have thoroughly checked for indentation errors and such. I also did extensive research on for and if statements such as here and here .

As far as my understanding goes, since the return statement is nested in for u in user_table: it should be going through all iterations of the users. I've been at this all day and can't see what I'm missing. Any help is much appreciated! (Also I know I spelled "pippen" wrong lol)

You are simply printing at the end of each iteration in the first code example, however in the flask example you are returning that. Return stops execution of the function it is in, returns a value (None if not specified) and then moves on. You should aggregate the values into a list or set and return that to the caller to parse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM