Python Continue statement with for loops

Hi,
In terms of loops lecture with continue statement, can anyone shed light what is the different between those two below?
Why do we need to put print in the end not before to have age only more than 21?

ages = [12, 38, 34, 26, 21, 19, 67, 41, 17]

for age in ages:
  if age<21:
    continue
  print(age)


for age in ages:
  print(age)
  if age<21:
    continue

Hello @jiyeonjang7025175947. The reason the first one works is that the continue keyword effectively skips the iteration; skipping past any code within the loop that comes after it. The second one will print the age no matter what it is. The first one; however, will only print the age if the continue isn’t executed.
I hope this helps!

6 Likes

:smiley: Thanks a lot indeed now it makes sense to me!

1 Like

Also note that this

for age in ages:
  print(age)
  if age<21:
    continue

is effectively the same as this

for age in ages:
  print(age)

because a loop “continues” to the next iteration anyway when it reaches the end of the loop.

1 Like