Continue iteration with changed parameters after met condition

Viewed 57

I need to change parameters outside the loop and continue iteration after specific condition is met.

For example, I have list of pizzas and as list of strings. I have list of sauce packs whci should be switched after condition is met. If there is a condition 'sauce_error' in string, I need to switch to another sauce pack from list of sauce packs and continue iteration using next sauce pack.

#list of sauce packs
saucePacks = ['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4']
index = 0
saucePack = saucePacks[index]

#list of pizzas
pizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']

#iterating over strings
for pizza in pizzas:  
  if 'sauce_error' in pizza:
    index = index+1 #need to switch sauce pack if substring in string
    print(saucePack, pizza)
  else:
    print(saucePack, pizza)

sauce pack should be switched to the next from list when 'sauce_error' occures in 'pizza' string.

desired output:

sauce_pack1 pizza1
sauce_pack1 pizza2
sauce_pack2 pizza3_sauce_error
sauce_pack2 pizza4
sauce_pack2 pizza5
3 Answers

You just forgot to update your saucePack with the new index:

#list of sauce packs
saucePacks = ['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4']
index = 0
saucePack = saucePacks[index]

#list of pizzas
pizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']

#iterating over strings
for pizza in pizzas:  
    if 'sauce_error' in pizza:
        index = index+1 #need to switch sauce pack if substring in string
        saucePack = saucePacks[index]
        print(saucePack, pizza)
    else:
        print(saucePack, pizza)

Tobias P.G. has the correct answer however, I made a few additions. Please use the code if it makes sense to you.

#list of sauce packs
saucePacks = ['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4']
index = 0

#list of pizzas
pizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']

#iterating over strings
for pizza in pizzas:  
  if 'sauce_error' in pizza:
    index += 1 #need to switch sauce pack if substring in string
    print(saucePacks[index], pizza)
  else:
    print(saucePacks[index], pizza)

Instead of updating an index and taking the new element according to it, it will be more Pythonic to use an iteraor:

#list of sauce packs
saucePacks = iter(['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4'])
saucePack = next(saucePacks)

#list of pizzas
pizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']

#iterating over strings
for pizza in pizzas:  
    if 'sauce_error' in pizza:
        saucePack = next(saucePacks)  # takes the next sauce from the list
    print(saucePack, pizza)

Please note that you need to be careful when the iterator is exhausted (which you also need to do with an index in case it passes the list's size...)

Related