python - How are the results for count different in all these three cases? -


code 1:

iteration = 0  count = 0  while iteration < 5:      letter in "hello, world":          count += 1      print "iteration " + str(iteration) + "; count is: " + str(count)      iteration += 1 

code 2:

iteration = 0  while iteration < 5:      count = 0      letter in "hello, world":          count += 1      print "iteration " + str(iteration) + "; count is: " + str(count)      iteration += 1 

code 3:

iteration = 0  while iteration < 5:      count = 0      letter in "hello, world":          count += 1          if iteration % 2 == 0:              break      print "iteration " + str(iteration) + "; count is: " + str(count)      iteration += 1 

for code 1, you're continuing add on count. during first iteration, count becomes 12 (the length of "hello, world" 12), , during second iteration, never reset count 0 count continuously added on until reaches 24, adds on length of "hello, world" again (12 + 12 = 24).

0 + len("hello, world") = 12  12 + len("hello, world") = 24  , forth 

for code 2, count reset 0 each time. means count equal 12, length of "hello, world" 12.

0 + len("hello, world") = 12  reset 0   0 + len("hello, world") = 12  , forth 

for code 3, break every time iteration number. means iterations 0, 2, , 4, iteration returns value of 1 1 added iteration @ beginning of loop. during odd iterations, count 12, since program not break out of loop , adds length of "hello, world", 12.

count = 0  loop      "h" in "hello, world"       add 1, 0 -> or odd? even, not add len("ello, world") count  1  count = 0  loop      "h" in "hello, world"       add 1, 0 -> or odd? odd, add len("ello, world") count  12 

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 -