Question regarding for loop continue keyword in Python

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-python-loops/lessons/learn-python-loops/exercises/continue
I was playing around with continue keyword in the for loop
def odd_numbers(lst):
for i in lst:
if i%2==0:
continue
return (i)
print(odd_numbers([2,8,7,16,25,1,5]))
when i ran this code, the output i got was just the first odd number 7

def odd_numbers(lst):
for i in lst:
if i%2==0:
continue
return (i)
print(odd_numbers([2,8,7,16,25,1,5]))
when i ran this code,output i obtained was the last odd number 5

I couldn’t understand understand the output even though both are unexpected output. Can anyone please guide me to understand this problem

Hello @py8645663567, welcome to the forums! Could you please post the code with the indenting preserved? To do this, press this button:


and insert the code between the back ticks:Screen Shot 2020-05-02 at 14.06.13


The first example presumably is indented like this:

for i in lst:
  if i%2 == 0:
    continue
  return (i)

In this code, the loop iterates through the lst list. Firstly, it checks for the item in the list i to see if it is divisible by two (by use of modulo). If it is, then that iteration is skipped, meaning no more of the list is executed for that iteration. If, however, the number i is not divisible by two, the rest of the code in the loop is executed, which is the return (i) line. A return keyword exits the function, and so exits any loop inside the function-hence why the first odd number is returned.

I would need to see the second example properly indented to be able to help with that.
I hope this helps!

Sorry for the mistake. In the second code, return (i) keyword indented with respect to for loop

def odd_numbers(lst):
   for i in lst:
     if i%2==0:
      continue
   return (i)
print(odd_numbers([2,8,7,16,25,1,5])) 

Here, I believe the reason this function (with the return i indented inline with the for-loop), returns the last item of the list, is because that was the last value of the variable i.

With each iteration over the loop, the variable i takes a new value-the next value in the list. When the list ends, the variable i is not deleted, so it still stores the last value that was assigned to it-the last value of the list. In this case, that would be 5.

I hope this helps!

Thank you, I finally understood the reason behind my output

1 Like