When does a loop with <continue> command stop?

Reviewing Loop concepts. Not understanding why the correct answer to the question below is Mamba. My thinking is that there will not be a last value because the loop will just continue to go round and round since the command will breeze through Cobra and Python and loop back to Viper … over and over again…

Determine the last value that will be printed in the console after the Python code block finishes execution.

snakes = ['Viper', 'Mamba', 'Cobra', 'Python']
for snake in snakes:
  if snake == 'Cobra':
    continue
  elif snake == 'Python':
    continue
  print(snake)

Thank you in advance for your help.

In the example given, it will stop when the data objects have all been examined. continue does not alter the loop parameters, only aborts the current iteration. As both of the test values are at the end of the list, it follows that the last item to print will be ‘Mamba’. How can we be so sure? The print statement is inside the loop and continue above means that line is skipped.

1 Like

Thanks for your response! I will hold on to your explanation: “…it will stop with the data objects have all been examined.” Ok!

At the end of your explanation you said that we can be sure 'Mamba" will be the last item to print because the print statement is inside the loop. So what happens if the print statement is outside of the loop? Will the output be what I think below? …

Viper
Mamba

2 Likes

If the print statement is outside of the loop then the only value printed will be the last value, ‘Python’. In Python, the value of the iterator variable is allowed to leak out of the loop body.

>>> snakes = ['Viper', 'Mamba', 'Cobra', 'Python']
>>> for snake in snakes:
      if snake == 'Cobra':
        continue
      elif snake == 'Python':
        continue


>>> print(snake)
Python
>>> 
1 Like

Oh yes that’s right! The print outside of the loop function is in global (territory? I forgot that term). Anyway, so since it is not in local (territory?) inside the loop function, the "for snake in snakes: … " won’t apply.

Thank you!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.