Trying to understand nested loops

Dan Stromberg drsalists at gmail.com
Fri Aug 5 18:50:49 EDT 2022


On Fri, Aug 5, 2022 at 12:35 AM <ojomooluwatolami675 at gmail.com> wrote:

> Hello, I’m new to learning python and I stumbled upon a question nested
> loops. This is the question below. Can you please how they arrived at 9 as
> the answer. Thanks
>
> var = 0
> for i in range(3):
>   for j in range(-2,-7,-2):
>     var += 1
>      print(var)
>

A debugger is useful for more than debugging; it can also help give an
intuition for control flow.  If you single step through this snippet with a
debugger, you'll probably see what's happening.

Of if you don't have (or want) a debugger, you could change it to:

var = 0
for i in range(3):
  print('i is', i)
  for j in range(-2,-7,-2):
    print('j is', j)
    var += 1
    print(var)

And note that 3 times 3 is 9.


More information about the Python-list mailing list