Aamir Rind
Aamir Rind

Reputation: 39709

repeat an iteration of for loop

if for some reason i want to repeat the same iteration how i can do it in python?

for eachId in listOfIds:
    #assume here that eachId conatins 10
    response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
    if response == 'market is closed':
       time.sleep(24*60*60) #sleep for one day

now when the function wake up from sleep after one day (market (currency trade market) is open) i want to resume my for loop from eachId = 10 not from eachId = 11, because eachId = 10 is not yet been processed as market was closed, any help is highly appreciated thanks.

Upvotes: 33

Views: 82098

Answers (4)

etuardu
etuardu

Reputation: 5546

i = 0
while i < len(listOfIds):
    eachId = listOfIds[i]
    #assume here that eachId conatins 10
    response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
    if response == 'market is closed':
       time.sleep(24*60*60) #sleep for one day
    else:
       i += 1

Upvotes: 2

eph
eph

Reputation: 2028

for eachId in listOfIds:
    while makeRequest(eachId) == 'market is closed':
       time.sleep(24*60*60) #sleep for one day

As @David added, if you don't need to capture response.

Upvotes: 0

Geo
Geo

Reputation: 96997

Use a while loop?

counter = 0
while counter < len(listOfIds):
  # do processing
  counter = counter + 1

And just don't increment, if you get 'market is closed'.

Upvotes: 9

David Heffernan
David Heffernan

Reputation: 613582

Do it like this:

for eachId in listOfIds:
    successful = False
    while not successful:        
        response = makeRequest(eachId)
        if response == 'market is closed':
            time.sleep(24*60*60) #sleep for one day
        else:
            successful = True

The title of your question is the clue. Repeating is achieved by iteration, and in this case you can do it simply with a nested while.

Upvotes: 50

Related Questions