[Tutor] While Loop Question

Steven D'Aprano steve at pearwood.info
Thu May 11 10:15:15 EDT 2017


On Wed, May 10, 2017 at 06:53:21PM -0700, Rafael Skovron wrote:
> Sorry I left out the indents in my previous email. It seems like j is
> always reset to zero. Why does j vary?

Because you run code that adds 1 to j.


> Are there two different instances of j going on?

No. Try to run the code in your head and see what happens. See below:

> for i in range(1, 5):
>     j=0
>     while j < i:
>          print(j, end = " ")
>          j += 1

We start by setting i = 1, then the body of the for-loop begins. That 
sets j = 0, and since 0 < 1, we enter the while-loop.

Inside the while-loop, we print j (0), then add 1 to j which makes it 1. 
Then we return to the top of the while-loop. Since 1 is NOT less than 1, 
we exit the while-loop and return to the top of the for-loop.

Now we set i = 2, and continue into the body of the for-loop. That sets 
j = 0 (again!) and since 0 < 2, we enter the while-loop.

Inside the while-loop, we print j (0), then add 1 to j which makes it 1. 
Then we return to the top of the while-loop. Since 1 < 2, we continue 
inside the body, print j (1), then add 1 to j which makes it 2. Since 2 
is not LESS than 2, we exit the while-loop and return to the top of the 
for-loop.

Now we set i = 3, and continue into the body of the for-loop. That sets 
j = 0 (again!) and since 0 < 3, we enter the while-loop.

Inside the while-loop, we follow the same steps and print 0, then 1, 
then 2, then exit the while-loop and return to the top of the for-loop.

Now we set i = 4, and again continue into the while-loop to print 0, 1, 
2 and finally 3, then exit the while-loop and return to the top of the 
for-loop, which is now complete.



-- 
Steve


More information about the Tutor mailing list