0

I have the following while loop:

while pointer < len(stack):
    temp_string +=1
    if stack[pointer] == "[":
        break

    pointer +=1

Now, I know that the break statement will cause the while loop to terminate, but am I right to say that as long as there is a break statement within the while loop (in any scope), as soon as it is reached, we break out of the while loop? i.e:

while pointer < len(stack):
    temp_string +=1
    if stack[pointer] == "[":
        if ....: 
            if ...: 
                break
    
    pointer +=1

So for the above, once we hit the break, it will break out of the while loop? Is this correct? And does the same apply to while loops within while loops?

  • 5
    Why don't you try? – Guy Jun 21 '21 at 12:48
  • 3
    It breaks out of the inner most loop you are in – Sayse Jun 21 '21 at 12:49
  • Also, see [the docs](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) – Sayse Jun 21 '21 at 12:49
  • Where are the scopes? Are you talking about the if-statements? Cause they don't create scope; [Python doesn't have block-scoping](/a/6167952/4518341). – wjandrea Jun 21 '21 at 12:52
  • 1
    Ohh thanks wjandrea- I assumed that each 4 spaces is a new scope. But now I understand this is not necessarily the case! – patrick chong Jun 21 '21 at 12:59
  • "Scope" is usually reserved to talk about the namespace in which a variable name is defined, although one could overload the term to refer to the loop which a particular `break` statement applies to. `if` is not a loop, so it's not relevant. – chepner Jun 21 '21 at 13:15
  • I see! This makes so much more sense now. Thanks chepner the explanation helps a lot – patrick chong Jun 21 '21 at 13:17

0 Answers0