python - Initialising value within or before "For Loop" -


i not understand why putting initial value of patriots_wins in , before loop make such difference.

output 0 wrong

# nfl data loaded nfl variable.  item in nfl:     patriots_wins = 0     if item[2] == "new england patriots":         patriots_wins = patriots_wins + 1  print(patriots_wins) 

correct answer

# nfl data loaded nfl variable.  patriots_wins = 0 item in nfl:     if item[2] == "new england patriots":         patriots_wins = patriots_wins + 1  print(patriots_wins) 

the reason not working correctly each time loop executes, reset value of wins 0, because statements in loop's body executed.

however if declare , initialize outside of loop, not "reset" within loop, incremented @ each iteration of loop. end result being variable has total number of wins.

to see how working, here example script supposed count number of 'a' in list:

>>> items = ['a','a','b','c','d','a'] >>> total_a = 0 >>> 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, count_a stays @ 1.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -