-1
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 summer_of69([2,5,6,9,11]), how 9 is getting ignored and 11 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 is it working for 9 and 11?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • Have you tried stepping through the code using a debugger in a good IDE? It adds numbers up to the first 6, then skips a followup 9 and adds what follows - if there's no 9 following the 6 it doesn't get back to adding. What the point of this code is, is unsure, but that's what it does. – Grismar Jul 16 '22 at 15:59
  • 1
    Pretend you are the interpreter. Instead of trying to do it in your head, use pencil and paper and execute each statement in sequence recording the result on the paper - keep track of variables, function arguments, conditional results. – wwii Jul 16 '22 at 15:59
  • [How to step through Python code to help debug issues?](https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues) If you are using an IDE **now** is a good time to learn its debugging features Or the built-in [Python debugger](https://docs.python.org/3/library/pdb.html). Printing *stuff* at strategic points in your program can help you trace what is or isn't happening. [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – wwii Jul 16 '22 at 15:59
  • [Visualize execution](https://pythontutor.com/visualize.html#mode=edit) – wwii Jul 16 '22 at 16:01

1 Answers1

0

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.

iamjaydev
  • 142
  • 8
Zarquon
  • 146
  • 8