syntaxError: 'continue' not properly in lo

2019-06-16 19:10发布

问题:

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.

回答1:

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)


回答2:

The problem might be in the way you are using continue

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or finally statement within that loop.6.1It continues with the next cycle of the nearest enclosing loop.