For/Else Statement Not Producing Expected Result

I am currently working on the Learn Python 2 course and am in the Loops lesson on the last module “Create your own”.

The for/else statement that I have written is as follows:

apple_types = ["McIntosh", "Granny Smith", "Red Delicious"]

for t in apple_types:
  if t == "McIntosh":
    print "Mc not Mac"
else:
  print t
  

This is producing the following output:

Mc not Mac
Red Delicious

Since, from my understanding, the “else” section of a for/else statement will always execute after the “for” section unless there is a break, the output I expected is:

Mc not Mac
McIntosh
Granny Smith
Red Delicious

Could someone please explain to me why the output I am getting is not what I expected?

1 Like

That will not be in the output since the if statement causes the other string to be printed. The else in your statement should be part of the if, not the for. Not enough indentation.

2 Likes

The else block of a for/else statement executes only after the for loop has completed all of its iterations without being interrupted by a statement such as a break, rather than after each iteration of the for loop. That is why this statement executes only once:

  print t

If you modify your code based on @mtf’s suggestion, associating the else block with the preceding if block, this would be the output:

Mc not Mac
Granny Smith
Red Delicious

Note that with such a modification, it would no longer be a for/else statement.

3 Likes

Understood. Thank you!

2 Likes