Free video project · Beginner
Football league table ⚽
Turn a list of results into a proper league table: points, goal difference, goals scored, sorted and printed in neat columns.
The video is out Friday 13 November at 6pm.
The code from the video
# Build a football league table from results
RESULTS = [("Rovers", 2, "United", 1), ("City", 0, "Athletic", 0), ("United", 3, "City", 1),
("Athletic", 1, "Rovers", 1), ("Rovers", 0, "City", 2), ("United", 2, "Athletic", 2),
("City", 1, "Rovers", 1), ("Athletic", 0, "United", 1), ("Rovers", 4, "Athletic", 0),
("City", 2, "United", 2), ("United", 1, "Rovers", 3), ("Athletic", 2, "City", 1)]
table = {}
def add(team, scored, conceded):
if team not in table:
table[team] = {"P": 0, "W": 0, "D": 0, "L": 0, "GF": 0, "GA": 0, "Pts": 0}
row = table[team]
row["P"] += 1
row["GF"] += scored
row["GA"] += conceded
if scored > conceded:
row["W"] += 1
row["Pts"] += 3
elif scored == conceded:
row["D"] += 1
row["Pts"] += 1
else:
row["L"] += 1
for home, home_goals, away, away_goals in RESULTS:
add(home, home_goals, away_goals)
add(away, away_goals, home_goals)
def sort_key(team):
row = table[team]
return (row["Pts"], row["GF"] - row["GA"], row["GF"])
print("Pos Team P W D L GF GA GD Pts")
for pos, team in enumerate(sorted(table, key=sort_key, reverse=True), 1):
r = table[team]
gd = r["GF"] - r["GA"]
print(f"{pos:>3} {team:<9}{r['P']:>2}{r['W']:>3}{r['D']:>3}{r['L']:>3}{r['GF']:>4}{r['GA']:>3}{gd:>+4}{r['Pts']:>4}")
Run it in your browser with nothing to install, right here on this page.
Make it your own
- Add a form column showing each team's last three results as W, D or L.
- Read the results from lines like "Ash 2-1 Elm" instead of tuples.
- Mark the top two as promoted and the bottom one as relegated.
Skills: tuples, dictionaries, sorting with a key, f-strings