How Can I Use An Exception Inside An While Loop? List Index Out Of Range
I have the following function: def findTweetWith100PlusRTs(): global tweet_main while tweet[tweet_main]['retweet_count'] < 100: tweet_main += 1 It loops through
Solution 1:
While you can make this work, you should be using a for loop:
# this is a proper use of while! :-)whileTrue:
for current_tweet in tweet:
if current_tweet["retweet_count"] < 100:
# do something with current_tweetpass
time.sleep(120)
refreshTL() # make sure you put a new list in `tweet[tweet_main]`
If, as can be guessed, refreshTL()
adds more tweets, you should read on generators and iterators, which are what you want to be using.
A very simple example of an endless tweet generator would be:
deftweets_generator():
tweets = NonewhileTrue:
# populate geneartor
tweets = fetch_tweets()
for tweet in tweets:
# give back one tweetyield tweet
# out of tweets, go back to re-populate generator...
The generator is constantly re-filled with tweets if you implement fetch_tweets
. Now you can do something like:
# only take tweets that have less than 100 retweets thanks @Stuart
tg = (tweet for tweet tweet_generator() if tweet['retweet_count'] < 100)
for tweet intg:# do something with tweet
Solution 2:
You could do it like this
deffindTweetWith100PlusRTs():
global tweet_main
whileTrue:
try:
if tweet[tweet_main]["retweet_count"] >= 100:
breakexcept IndexError:
# do something
tweet_main += 1
Post a Comment for "How Can I Use An Exception Inside An While Loop? List Index Out Of Range"