def summer_of69(arr):
total =0
add = True
for num in arr:
while add:
if num!= 6:
total =num
break
else:
add = False
while not add:
if num!=9:
break
else:
add= True
break
return total
In this code if I pass summerof_69([2,5,6,9,11])? how 9 is getting ignored and 11 is getting added? The output I am getting 18 is correct but i want to know how 2nd while loop is working here! after 6 how its working for 9 and 11?
CodePudding user response:
In order to understand how any complex system of loops works you just have to go through the code step by step and evaluate the logic the way the computer does.
When num becomes 6, think about what happens when it goes through both while loops.
The first while loop does not add 6 to total and instead turns the variable add to False.
Since add is now False the second while loop triggers but then immediately breaks.
Now num is 9 and since add is False the first while loop does not execute.
Instead the second one does and add becomes True.
Finally, now that add is True, when num is 11, the first while loop executes, adding 11 to the total and the second while loop does not.
It just takes a moment to think it through in your head, and if it ever becomes too complicated to do in your head, there are plenty of visualize execution programs out on the web that do it for you.
