I am using python range() with for loop but situation is 2 loops, expect the outer loop run once, then inter loop runs completely, then outer loop runs its 2nd... question: why the outer loop run twice before the inter loop get a chance to run?
What I have tried:def sort(a_list):
for i in range(1,len(a_list)):
print("i=",i)
for j in range(i-1,0,-1):
print("j=",j)
Test: L=[9,6,1,3]
sort(L)
Result:
i= 1
i= 2 # here, the outer lopp ran twice then inter loop began.
j= 1
i= 3
j= 2
j= 1
解决方案If you want to find out exactly how this code work, use the debugger. It's there to debug YOU and your understanding of the code.
It appears the i loop executes twice in a row because it doesn't. The inner j loop executes but range returns an array of values from i - 1 to 0, with the upper limit of 0 being non-inclusive.
On the first iteration of i, that would be range(1 - 1, 0, -1), which will return no values for the j loop.
This is the expected behavior.
Look at the values of your inner loop. The first time it runs the variable i holds the value 1. So the loop will not run since i - 1 is zero, and the loop is defined to run from values zero to zero.
Quote:why the outer loop run twice before the inter loop get a chance to run?
For a good explanation, read the documentation:
4. Built-in Types — Python 3.7.0 documentation[^]