Biggen
Biggen

Reputation: 295

Two sets of similar python code seem to act differently

Trying to figure out why I'm getting two different results here (one that is an error). Here is the code that runs:

hta = 2.13
visitor_team_ratings = [21.53]
home_team_ratings = [None]
difference = []

for a, b in zip(visitor_team_ratings, home_team_ratings):
    if a and b:
        difference.append(a - (b + float(hta)))
    else:
        difference.append('NO RATING')
print(difference)

This prints out "NO RATING" but I'm hard pressed to understand why it does that. None isn't the same thing as an empty list so why is python dropping down to the else statement.

Here is similar code that throws an error. Same variables/list as the working code above:

if visitor_team_ratings and home_team_ratings:
    difference.append((visitor_team_ratings[0] - (home_team_ratings[0] + float(hta))))
else:
    difference.append('NO RATING')
print(difference)

The error is: TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'

I'm not sure I understand why one works and one doesn't. And the one that does work, I'm not even sure I understand why it does that. I've been using that 1st code block in my program for a while...

Upvotes: 1

Views: 89

Answers (4)

unknown
unknown

Reputation: 251

In the first block, you are looping through the elements of list. Inside the loop, you are evaluating weather elements(a and b both) are true or not. Clearly, None is not true that's why it moves to the else part.

In the second part, you are evaluating whether two lists are true or not. Lists are not empty so if part is executed.

Upvotes: 0

Nuageux
Nuageux

Reputation: 1686

In if visitor_team_ratings and home_team_ratings:̀ you look at the lists.

Whereas if you use: if visitor_team_ratings[0] and home_team_ratings[0]:. Then you look at the element inside the lists. (Which correspond to a and b of your first block)

edit I should elaborate more:

home_team_ratings = [None]

This is the cause of your problem. If you look at the element, it's None so the condition won't be True. But if you look at the list, then your if will be True since both lists are not empty. But right after home_team_ratings[0]: will give an error since it's None.

Upvotes: 2

khelwood
khelwood

Reputation: 59146

The issues are mainly down to this:

home_team_ratings = [None]

In the first version, when you write

if a and b

b is None, because it came out of home_team_ratings. So the if condition is false.

In the second version

if visitor_team_ratings and home_team_ratings:

This condition is true, because neither list is empty. But then (home_team_ratings[0] + float(hta)) throws an exception, because you are trying to add None to a float.

Upvotes: 2

blue note
blue note

Reputation: 29099

In the first example if a and b evaluates to False, since bool(None) is False. In the second example, the list [None] evaluates to True, since it is not empty

Upvotes: 0

Related Questions