Conditional That Tests For A Dictionary Key's Presence Is Always False
Solution 1:
In Python, all comparisons have the same precedence, including in
.
What's happening is comparison chaining, a special form intended to test transitive relationships like in math class:
if x_min < x < x_max:
...
As Paweł Kordowski pointed out in his comment, the above comparison chain is mostly equivalent to:
if x_min < x and x < x_max:
...
(There is one difference:
The "equivalent" code might evaluate x
twice, while the comparison chain evaluates x
exactly once.)
In your case, the comparison chain is:
if team in curr_stats == False:
...
...which is (mostly) equivalent to:
if team in curr_stats and curr_stats == False:
...
This is only true if curr_stats
contains team
and curr_stats
is empty... which should never happen.
The problem with your code is the == False
--- in part because it turned a comparison into a comparison chain, but mostly because you never needed it in the first place.
Python provides the not
keyword for when you want a Boolean's opposite.
Your conditional statement should read:
if team not in curr_stats:
invalid = invalid + 1
One last suggestion:
This function can be made even shorter by getting rid of the invalid
counter and just returning as soon as an invalid team
is found.
(Once the you've discovered that weekly_result
is invalid input, you probably don't care if it's "even more invalid".)
I also used dict.items
to simplify the final for
loop:
def update_standings(curr_stats, weekly_result):
point_counter(weekly_result)
for team in weekly_result:
if team not in curr_stats:
print(invalid_msg)
return
for team, result in weekly_result.items():
curr_stats[team] += result
Post a Comment for "Conditional That Tests For A Dictionary Key's Presence Is Always False"