Search code examples
pythonfor-loopif-statementnested-loops

Unexpected result from nested for loop - Python


I'm trying to run a nested for loop with a conditional statement. When running it, I expect it to print the statement that I defined if my conditional statement. But it doesn't print anything. (and it doesn't run indefinitely). Pokemons_gyms is a list of strings. Players is a dictionary. I tried adding else: continue but it doesn't work. I'm stuck cause I don't get any error running the code...

pokemon_gyms = ['reddit.com', 'amazon.com', 'twitter.com', 
            'linkedin.com', 'ebay.com','netflix.com',
            'udacity.com','stackoverflow.com','github.com',
            'quora.com']

players= {
    1: {
        'gyms_visited': ['amazon.com', 'ebay.com']
        }
    2:{
        'gyms_visited' : ['stackoverflow.com','github.com']
      }
}

for gym in pokemon_gyms:     
    for players_id in players:
        if gym == players[players_id]['gyms_visited']:
            print(str(players[players_id]['player_name']) +" has visited "+ str(gym))

Solution

  • players[players_id]['gyms_visited'] returns a list so gym == players[players_id]['gyms_visited'] always evaluates to False.

    You should check for membership using in:

    if gym in players[players_id]['gyms_visited']:
        ...