fuhrerguxez fuhrerguxez - 24 days ago 7
Python Question

Print something just once in a for loop

I have a bot that is using the League of legends API. I just want to retrieve some stats from a specific match. I had the code working but it was long and repetitive and I wanted to clean it up. Right now the main function of the code is working but before I put it in the bot I am doing some tests. Right now this is the code, I'll explain it.

for i in range(0, 9):
num += 1
i = r_match['participants'][num]
e_name = i['summonerName']
e_id = i['summonerId']
team_id = i['teamId']

r_team = requests.get("https://lan.api.pvp.net/api/lol/lan/v2.5/league/by-summoner/{}/"
"entry?api_key=".format(e_id)).json()

x = r_team["{}".format(e_id)][0]
e_tier = x['tier']
e_div = x['entries'][0]['division']

if team_id == 100:
print("Blue team")
print(e_name, e_tier, e_div)

elif team_id == 200:
print("Red team")
print(e_name, e_tier, e_div)


So this part of the code gets the name of the participants of the match, it gets their id and with that id it finds some other stats. There are two teams. In the Json response each team has an Id. 100 and 200 as you can see here:

if team_id == 100:
print("Blue team")
print(e_name, e_tier, e_div)

elif team_id == 200:
print("Red team")
print(e_name, e_tier, e_div)


What I want to do is print "Blue team" and "Red Team" just once when the condition is met. This is so I can print it nice a clean to the chat where the bot is working but everytime I run the code "blue team" or "red team" for each participant of the match, let's say:

Blue Team
player 1
Blue Team
player 2...


And so on until there are 10 players in total printed out. What I want to do is:

Blue Team
player1
player2
player3
player4
player5

Red Team
player6
player7
player8
player9
player10


And that's it. Thanks for any help :)

Answer
ids_seen = set ()

for i in range(0, 9):
    num += 1
    i = r_match['participants'][num]
    e_name = i['summonerName']
    e_id = i['summonerId']
    team_id = i['teamId']

    r_team = requests.get("https://lan.api.pvp.net/api/lol/lan/v2.5/league/by-summoner/{}/"
                          "entry?api_key=".format(e_id)).json()

    x = r_team["{}".format(e_id)][0]
    e_tier = x['tier']
    e_div = x['entries'][0]['division']


    if team_id == 100:
        if not team_id in ids_seen:
            print("Blue team")
        print(e_name, e_tier, e_div)

    elif team_id == 200:
        if not team_id in ids_seen:
            print("Red team")
        print(e_name, e_tier, e_div)

    ids_seen.add (team_id)