Loops/exercises/change-it-up

fruits = [‘banana’, ‘apple’, ‘orange’, ‘tomato’, ‘pear’, ‘grape’]
print ‘You have…’
for f in fruits:
if f == ‘tomato’:
print ‘A tomato is not a fruit!’ # (It actually is.)
print ‘A’, f
else:
print ‘A fine selection of fruits!’

Output
You have…
A banana
A apple
A orange
A tomato is not a fruit!
A tomato
A pear
A grape
A fine selection of fruits!

I wish to understand the logistic behind this output for the above mentioned code. How has for/else worked here?

Hello! The else belongs to the if statement. Essentially the code runs as so:
For every item (f) in the list fruits, run the following code:
If the item f equals the string tomato, then run this code:
Print to the console “A tomato is not a fruit”
Then, print “A”, followed by the item f
If the item f does not equal the string tomato, print A fine selection of fruits!.

I hope this helps!

1 Like

When the iteration of for loop takes place, only once does the condition of f==Tomato is satisfied. Thereafter follows the print A, f statement follows. Should not that result into the following output in console:
You have…
A tomato is not a fruit
A tomato
A fine selection of fruits!

It depends on the indenting of the code-sorry, I should have said that in my first reply. If it was like so:

for f in fruits:
   #code 
else:
  print("A fine selection of fruits!")

Then, yes, the else would be connected to the for, however that is very rarely used; more often, one would just leave the else off:

for f in fruits:
  #code 
print("A fine selection of fruits!")

I hope that helps!

1 Like