0

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)

CodeStardust
  • 5
  • 1
  • 6
  • At first glance this doesn't sound very surprising. `return` terminates the function call, but `print` doesn't. You seem to be describing standard behavior. – John Coleman Jan 23 '19 at 01:02
  • Ok thanks, I believe this is what you're saying: https://stackoverflow.com/questions/5864166/return-statement-in-for-loops However putting it outside the for loop I don't get all the info I need. It only returns `samwise [list]` when I do that. Do you have any suggestions? – CodeStardust Jan 23 '19 at 02:08

1 Answers1

1

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.

Theodore Howell
  • 419
  • 3
  • 12
  • Ok thanks (I'm not allowed to up vote sorry) Someone else pointed that out and I was just starting to realize that me also assigning the empty list inside the `for` loop was causing me to lose data as well. Thanks so much for taking time to explain this as that is common info about `return` and I missed it. – CodeStardust Jan 23 '19 at 03:34
  • No problem, just glad I can give someone else that moment since SO has provided me with such relief! – Theodore Howell Feb 12 '19 at 23:45