Reputation: 1482
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
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
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
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