python里for循环range,为什么Python range()在for循环中运行两次

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[^]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值