a couple q's from an intro to CS/Python online course that i didn't understand the answers to:
Code:
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
if iteration % 2 == 0:
break
print "Iteration " + str(iteration) + "; count is: " + str(count)
iteration += 1
"1. How many times will the print statement be exectued?
2. What is the smallest value of the variable count that will be printed out (at the print statement)?"
the answer to the first question is 5, but i don't see why. i thought it would be 3, because i thought the code takes iterations 0, 2, 4 (%2==0 and < 5) and break to the print statement only on those.
for the second question the answer is 1, and i think i understand how the program is interpreted, but i guess i don't understand why the interpretation is logical. i understand that "letter" is bound to "h" and the count is incremented by 1, and then apparently control is passed to the "if %2==0" conditional. but i don't understand why the count doesn't finish iterating through the string and binding "letter" to 2, 3, ....12, before going on to the "if" conditional.
fwiw here's the output of the code:
Code:
Iteration 0; count is: 1
Iteration 1; count is: 12
Iteration 2; count is: 1
Iteration 3; count is: 12
Iteration 4; count is: 1