What is the scope of a variable that is part of a for loop?

i = 15
ages = [12, 38, 34, 26, 21, 19, 67, 41, 17]
for i in ages:
  if(i<21):
    continue
print(i)
  

Shouldn’t the output be 15 but instead it is being shown as 17. As ‘i’ written in for loop should be within the loop? Any explantion?

Welcome, @gouthamuppalapati

You are correct. Since i is initialized in the for loop, it does not need to declared ahead of the loop.

What is this supposed be doing?

No. 17 is the expected output from your code. Even though you’ve declared i = 15 outside the scope of the for loop, the for loop still mutates i. Your variable declaration and the for loop are in the same scope. Try this:

i = 15
ages = [12, 38, 34, 26, 21, 19, 67, 41, 17]
def my_ages(ages):
  for i in ages:
    if(i<21):
      continue

my_ages(ages)
print(i)

Now what will the output be?

Here’s the instruction:

Your computer is the doorman at a bar in a country where the drinking age is 21.

Loop through the ages list. If an entry is less than 21 , skip it and move to the next entry. Otherwise, print the age.

The print statement needs to be indented, but it appears the op may have out dented it on purpose to test a theory regarding the scope of i.

Maybe I could see all that, but would be more satisfied with a response from the OP.