GOT STUCK on PYTHON with different code which outputs the same thing

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

for age in ages:
if age >= 21:
print(age)

print(" How is this happening ?")

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

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

output:

Output:
38
34
26
21
67
41
How is this happening ?
38
34
26
21
67
41

the problem with this code is that it will output the same result, despite having different code. Can somebody explain why this is happening?

Hi,
So, your for loop is going through the ages array one item at a time, storing each item in the variable age.
In the first loop, it’s asking is the value in age over or equal to 21. If it is, the code associated with the if statement will run (in this case it’ll print(age))
If it isn’t, then the loop will continue and it’ll go on to the next item in the list.

In the second loop, the if statement is asking the reverse. Is the value in age less than 21.
If it is, then the code that’ll be run is the continue line. This ends the current loop and goes onto the next item in the array. So, it skips the part of the loop with print(age).

In both cases the code, print(age), only gets run if age is greater or equal to 21.
You can often find several different ways to approach the same problem.

Have fun

1 Like

Thank you for the explanation. now it makes sense :slight_smile:

1 Like