Python Data Analysis Basics - 3. Converting Ages to Decades

What is the difference in these two codes that the system is marking me wrong? I did a print on the len of both lists and it’s the same length… ?

Mine:

decades = []
for age_nums in final_ages:
    if age_nums == 'Unknown':
        decade = 'Unknown'
        decades.append(decade)
    else:
        age_nums = str(age_nums)
        decade = age_nums[0] + '0s'
        decades.append(decade)
print(decades)

Dataquest’s

decades = []

for ages in final_ages:
    if ages == 'Unknown':
        decade = ages
    else:
        decade = str(ages)
        decade = decade[-1]
        decade = decade + '0s'
    decades.append(decade)

Thanks!

Hi @eugeniosp3
I think difference came from this ligne

you should change it by decade = age_nums[1] + '0s' or decade = age_nums[-1] + '0s' because you’re taking the first item on the list instead of the second.

Hi @eugeniosp3. The line for the solution code is actually decade = decade[:-1] (with the colon).

The problem has to do with ages over 99. For all the other ages, it’s fine to just take the first character with age_nums[0] because you’ll get 10s, 20s, 30s, 40s, etc. However, once you get to age 100, if we’re only taking the 1st string character, it will become “10s”. We actually want that to say “100s”!

The fix for this is to take all the string characters except the last one using age_nums[:-1]. Then 35 will still become 30s, 14 will still become 10s, but we’ll also correctly get that 103 will become 100s.

I hope that helps!

1 Like

Thanks April G. I too has the same query and I too wrote my code with [0] and was getting error.

I don’t understand why is it necessary to have a blank line after the first line?
Mine was wrong:
decades =
for age in final_ages:
if age == “Unknown”:
decade = age
else:
decade = str(age)
decade = decade[:-1]
decade = decade + “0s”
decades.append(decade)

And the one from DQ is the same but with a space after the first line:
decades =

for age in final_ages:
if age == “Unknown”:
decade = age
else:
decade = str(age)
decade = decade[:-1]
decade = decade + “0s”
decades.append(decade)