Kyle Treurnich
Kyle Treurnich

Reputation: 11

Adding a score from a list in python programming

This is my code:

 aliens = ['red_alien', 'blue_alien', 'blue_alien', 'green_alien', 
'red_alien', 'red_alien', 'red_alien', 'blue_alien', 'blue_alien', 
'green_alien'] 

current_score = 0

for alien in aliens:
    if 'red_alien' in aliens:
        current_score += 5

    elif 'green_alien' in aliens:
        current_score += 10

    elif 'blue_alien' in aliens:
        current_score += 20

print(current_score)

Currently, I'm unsure why the numbers aren't adding up correctly when the code is being run.

Upvotes: 1

Views: 721

Answers (3)

Akhilesh Pandey
Akhilesh Pandey

Reputation: 896

You can also try the following code. It may not provide additional benefits but still, it's another way of writing the same code.

alien_list= {'red_alien':5, 'green_alien':10, 'blue_alien':20}
current_score= 0
for alien in aliens:
    if alien in alien_list.keys():
        current_score += alien_list[alien]

print(current_score)

output: 120

Upvotes: 0

FHTMitchell
FHTMitchell

Reputation: 12157

You loop over aliens assigning each element to alien. But then you test if red_alien is in aliens (note the s) which is the whole list, not the alien. I think what you want is:

current_score = 0

for alien in aliens:
    if 'red_alien' == alien:
        current_score += 5

    elif 'green_alien' == alien:
        current_score += 10

    elif 'blue_alien' == alien:
        current_score += 20

print(current_score)

Upvotes: 2

ColdIV
ColdIV

Reputation: 1104

You are iterating over aliens with "alien"
So you can just compare 'red_alien' == alien
that should do the trick

Upvotes: 2

Related Questions