18 Change it up


#1



Loops


Does anyone know how to escape from printing a tomato in the list?


Replace this line with your code. 
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!'


#2

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.)
# break
elif f != 'tomato':
print 'A', f
else:
print 'A fine selection of fruits!'


#3

Thank you! interesting, that first it checks if f=='tomato' and print, and there is suppose to be no tomato, but then it needs to check again in order to escape printing. Do I understand it right?


#4

Actually, it checks whether each item is a tomato, if it is not a tomato, it does not run the "if" statement, because the statement is "False," it will move on to the elif statement. On the elif statement it will check if the item on the list is not a tomato, if it is "True", it will run the elif statement, which will print the item.

Note:
if/elif/else statements checks each statement until it reaches "True", which is why it had to check again.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.