Question

So, I'm having a bit of trouble with this piece of code.

if s.get("home") < s.get("away"):
        scoringplays = scoringplays + s.get("away") + "-" + s.get("home") + " " + game.get("away_team_name")
    elif s.get("home") > s.get("away"):
        scoringplays = scoringplays + s.get("home") + "-" + s.get("away") + " " + game.get("home_team_name")
    else:
        scoringplays = scoringplays + s.get("home") + "-" + s.get("away") + " Tied"

It pulls the score of a baseball game from MLB and posts it to reddit like so:

4-3 Winning Team Name

However, I've noticed if one of the scores is in double digits, the code seems to only read the first digit, so a score of 10-2 would display like so:

2-10 Losing Team Name

I've searched around a bit, and perhaps I'm using the wrong search terms, but I can't seem to find an answer in here. Any help would be greatly appreciated.

Was it helpful?

Solution

Looks like you're comparing strings:

>>> "10" < "2"
True

Compare their integer version:

if int(s.get("home")) < int(s.get("away"))

If the key is missing from the dict then dict.get returns None by default. You can also pass your own default value.

home_score = int(s.get("home", 0))  # or choose some other default value
away_score = int(s.get("away", 0))

if home_score < away_score:
     #do something

Demo:

>>> int("10") < int("2")
False
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top