syntaxError: 'continue' not properly in loop

anonuser0428 picture anonuser0428 · Jan 14, 2013 · Viewed 95.2k times · Source

I have been struggling with this error for a while now and there seems to be different opinions regarding why the interpreter complains about the 'continue'. So I would like to provide the erroneous code below.

import tweepy
import time
def writeHandlesToFile():
    file = open("dataFile.txt","w")
    try:
        list = tweepy.Cursor(tweepy.api.followers,screen_name='someHandle',).items(100000)
        print "cursor executed"
        for item in list:
            file.write(item.screen_name+"\n")
    except tweepy.error.TweepError as e:
        print "In the except method"
        print e
        time.sleep(3600)
        continue

The reason I am particular on including the continue at the end is because I would like for the program to restart execution at the top from where it left off after the sleep in order to preserve the program state. I need the sleep in order to abide by the twitter api rate limits wherein the api only allows you to make a certain number of requests every hour. So anyone who might see my mistake naive or otherwise please do point it out or please provide me with an alternative implementation without the use of the continue statement.

BTW I do not have tabs and spaces mixed as was suggested in another post. Thank you for your help in advance.

Answer

Tim picture Tim · Jan 14, 2013

continue is only allowed within a for or while loop. You can easily restructure your function to loop until a valid request.

def writeHandlesToFile():
    while True:
        with open("dataFile.txt","w") as f:
            try:
                lst = tweepy.Cursor(tweepy.api.followers,screen_name='someHandle',).items(100000)
                print "cursor executed"
                for item in lst:
                    f.write(item.screen_name+"\n")
                break
            except tweepy.error.TweepError as e:
                print "In the except method"
                print e
                time.sleep(3600)