問題描述
syntaxError:“繼續”在循環中不正確 (syntaxError: 'continue' not properly in loop)
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.
(by anonuser0428、Tim、Srikar Appalaraju)