Filtering for the intervals

https://app.dataquest.io/m/314/dictionaries-and-frequency-tables/13/filtering-for-the-intervals

I get an error when trying to use the “and” command as seen below. Why is that?

for row in apps_data[1:]:
    user_ratings = float(row[5])
    
    if user_ratings == 0:
        app_ratings['0 ratings'] += 1
    
    elif user_ratings >= 1 and <= 10:
        app_ratings['1 - 10 ratings'] += 1
        
    elif user_ratings > 10 and <= 100:
        app_ratings['10 - 100 ratings'] += 1
    
    elif user_ratings > 100 and <= 500:
        app_ratings['100 - 500 ratings'] += 1
        
    elif user_ratings > 500 and <= 1000:
        app_ratings['500 - 1000 ratings'] += 1
    
    elif user_ratings > 1000 and <= 10000:
        app_ratings['1000 - 10000 ratings'] += 1

Using this instead is rather confusing but it works:

for row in apps_data[1:]:
    user_ratings = float(row[5])
    
    if user_ratings == 0:
        app_ratings['0 ratings'] += 1
    
    elif 1 <= user_ratings <= 10:
        app_ratings['1 - 10 ratings'] += 1
        
    elif 10 < user_ratings <= 100:
        app_ratings['10 - 100 ratings'] += 1
    
    elif 100 < user_ratings <= 500:
        app_ratings['100 - 500 ratings'] += 1
        
    elif 500 < user_ratings <= 1000:
        app_ratings['500 - 1000 ratings'] += 1

1 Like

Hi @ea.enodiana:

Python compares variables individually. Thus:

 elif user_ratings >= 1 and <= 10:

is as good as saying:
else if the value stored in the variable user_ratings is greater than or equal to 1 or nothing is less than or equal to 10, thus throwing the error (since no variable is specified).

Using user_ratings this way is a bit similar to how we learnt inequalities (i.e. if user_ratings is between 1 and 10 inclusive–it checks if user_ratings is <=10 and user_ratings is >=1)

Hope this helps!

2 Likes

Hi Ryan,

why the need to put the = in any of the += in:

elif user_ratings > 500 and <= 1000:
            app_ratings['500 - 1000 ratings'] += 1

Shouldnt a simple + work?

This is a shorthand for app_ratings['500 - 1000 ratings'] = app_ratings['500 - 1000 ratings'] + 1, where we wish to increment the value of the key '500 - 1000 ratings' in the dictionary app_ratings.