18 else under if


#1



Can anyone please explain to me why these 2 outputs are different. One has "A tomato
"and the other one doesn't. Thank you!

The first code output:
You have...
A banana
A apple
A orange
A tomato is not a fruit!
A pear
A grape
A fine selection of fruits!
None

The second code 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!
None


###if...else...
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!'    
    else:
        print 'A', f
else:   
    print 'A fine selection of fruits!'

####if without else
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!'  
    print 'A', f
else:   
    print 'A fine selection of fruits!'


#2

well, this line:

print 'A', f

in the first code is only reached when the if condition evaluate to false (because of else), in the second code its reached regardless of the if condtion


#3

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