BabyishTank
BabyishTank

Reputation: 1482

if else statement does't work correctly

grade=['A good','B ok','C bad']
for item in grade:
    if item[0] == 'A':
        print('Excellent')
    if item[0] == 'B':
        print('Nice')
    else:
        print('Work harder')

I want A to just print 'Excellent' while B just print 'Nice', and c (else) print 'Work harder'. But both A and B print 'Work Harder', and C (else) doesn't print anything. What would be a way to fix this?

result

Excellent
Work harder
Nice
Work harder

Upvotes: 0

Views: 92

Answers (3)

Jonathan Zerox
Jonathan Zerox

Reputation: 140

You should do this.

grade=['A good','B ok','C bad']
for item in grade:
    if item[0] == 'A':
        print('Excellent')
    elif item[0] == 'B':
        print('Nice')
    else:
        print('Work harder')

the reason it didn't work is because you were handling two of the conditions separetely not as a single unit, if you're testing multiple values always use if - elif - else not if - if - else

Upvotes: 3

shree.pat18
shree.pat18

Reputation: 21757

You need the if-else if-else flow here. Just change the second if to elif

    grade=['A good','B ok','C bad']
    for item in grade:
        if item[0] == 'A':
            print('Excellent')
        elif item[0] == 'B':
            print('Nice')
        else:
            print('Work harder')

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49330

You're handling A separately from B and C. Connect them into a single structure with elif:

elif item[0] == 'B':

Upvotes: 2

Related Questions