Search code examples
pythonlistnested

Python nested loop: wrong output


The task is to complete a code to label each app as "below average", "roughly average", or "better than average" depending on its rating. Inside the for loop, If the app rating is less than 3.0, then label the app as "below average" by appending the string 'below average' to the current iteration variable. Else if the app rating is greater than or equal to 3.0 and below 4.0, then label the app as "roughly average" by appending the string 'roughly average' to the current iteration variable. Else if the app rating is greater than or equal to 4.0 label the app "better than average" by appending the string 'better than average' to the current iteration variable. Print app_ratings to see the results.

This is my code:

app=[]

app_ratings = [[
    'Facebook', 3.5],
    ['Notion', 4.0],
    ['Astropad Standard', 4.5],
    ['NAVIGON Europe', 3.5
]]

for app_ratings in app:
    app=[1]
    if app_ratings < 3.0:
        app.append('below average')

    elif   3.0 <= app_ratings < 4.0:        
        app.append('roughly average')

    elif app_ratings >= 4.0:
        app.append('better than average')

print(app_ratings)

Kindly advise on how I can correctly iterate over this nested list to achieve the correct output.


Solution

  • I think the below code is what you want. I think you want to append the 'average' string to the end of each element inside app_ratings list.

    app_ratings = [['Facebook', 3.5],
        ['Notion', 4.0],
        ['Astropad Standard', 4.5],
        ['NAVIGON Europe', 3.5]
    ]
    
    for app in app_ratings:
    #app[1] is the score (3.5, 4.0,...)
    #app is each element inside app_ratings (['Facebook', 3.5],...)
        if app[1] < 3.0: 
            app.append('below average')
        elif app[1] < 4.0:
            app.append('roughly average')
        else:
            app.append('better than average')
    
    print(app_ratings)
    #[    ['Facebook', 3.5, 'roughly average'],
    #    ['Notion', 4.0, 'better than average'],
    #    ['Astropad Standard', 4.5, 'better than average'],
    #    ['NAVIGON Europe', 3.5, 'roughly average']
    #]