-2

To go to the next word in a loop you just need to use the continue function.

Ex.

a = ['a', 'b', 'c', 'd']
for word in a:
    continue

But if the code is this:

a = ['a', 'b', 'c', 'd']
for word in a:
    for word2 in word:
        continue

The continue function works for the second loop, but I want something that works for the first loop and at the same time written in the second loop.

Edoardo
  • 5
  • 3

3 Answers3

0

Use the current index to help you navigate outside of the position of the loop. Enumerate builtin perfect for this.

a = ['a', 'b', 'c', 'd']
l = len(a)
for i, word in enumerate(a):
    nexti = i + 1
    nextword = a[nexti] if nexti <= l else None
    ...
skullgoblet1089
  • 554
  • 4
  • 12
0

You can use a variable to determent if you need to continue the second time:

a = ['a', 'b', 'c', 'd']
for word in a:
    for word2 in word:
        do_continue = true # Defining the variable
        continue
    if do_continue:
        continue
3174N
  • 188
  • 2
  • 14
0

You can break from the inner loop and use else to determine if the outer loop should continue.

a = ['aaaaxaaaa', 'bbbbbb', 'cccccxccc', 'ddddxddd']
for word in a:
    for letter in word:
        at_end=False
        if (letter == 'x'): break
        print(letter)
    else:    # only called at end of loop if no break
        at_end = True
    if (at_end == False): continue  # inner loop exited early
    print(word)
Mike67
  • 11,175
  • 2
  • 7
  • 15