-1

I do not understand why putting the initial value of patriots_wins in and before the for loop would make such a difference.

Output was 0 which was wrong

# The nfl data is loaded into the nfl variable.

for item in nfl:
    patriots_wins = 0
    if item[2] == "New England Patriots":
        patriots_wins = patriots_wins + 1

print(patriots_wins)

Correct answer

# The nfl data is loaded into the nfl variable.

patriots_wins = 0
for item in nfl:
    if item[2] == "New England Patriots":
        patriots_wins = patriots_wins + 1

print(patriots_wins)
Victor Yip
  • 295
  • 1
  • 5
  • 11

3 Answers3

2

The reason its not working correctly is each time the loop executes, you reset the value of wins to 0, because all the statements in the loop's body are executed.

However if you declare and initialize it outside of the loop, then it is not "reset" within the loop, it is just incremented at each iteration of the loop. The end result being that the variable has the total number of wins.

To see how this is working, here is an example script that is supposed to count the number of 'a' in a list:

>>> items = ['a','a','b','c','d','a']
>>> total_a = 0
>>> for item in items:
...   count_a = 0
...   if item == 'a':
...      count_a += 1
...      total_a += 1
...      print('count_a: {}'.format(count_a))
...      print('total_a: {}'.format(total_a))
...
count_a: 1
total_a: 1
count_a: 1
total_a: 2
count_a: 1
total_a: 3

You can see how each time total_a keeps getting incremented, but count_a stays at 1.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

At each loop of the for you insert a zero into the integer and then it will keep be zero untill the end of the loop. So:

patriots_wins = patriots_wins + 1

Won't matter because right after that

patriot_wins=0
Nitzan Farhi
  • 175
  • 2
  • 12
0

By putting patriots_wins = 0 within the for loop, you are resetting the value to 0 at the beginning of each iteration of the for loop.

Therefore, the value (which is supposed to be the accumulated # of patriots_wins) is wrong for the first approach.

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41