为什么这个while循环不输出[]

img


a每次都减小一个,a肯定不等于f(a)啊,为什么这个while循环只执行了一次?

执行了一次else里面的pop就return了
你应该把else里面的return写到和if else同一层,这样才行

  • 复刻您的代码运行效果截图

    img


    while循环确实只执行了一次f(a)。
#!/sur/bin/nve python
# coding: utf-8

def f(s):
    
    if s == []: #这一行可以写成下面的样子。
    #if not s: # “空”就是False。
        return []
    else:
        s.pop()
        return s

a = list(range(1,6))
print(f"\n列表a:{a}, Id: {id(a)}") 

while a != f(a):
    print(f"\nwhile内调用f(a)函数前返回的列表a:{a}, Id: {id(a)}")
    a = f(a)
    print(f"\nwhile内调用f(a)函数后返回的列表a:{a}, Id: {id(a)}")

print(f"\n最后列表a:{a}, Id: {id(a)}") 

您的while循环执行的条件,设置得不合理,您的while循环体内的语句根本就没有执行过,就第一次判断时执行了一次,且返回了False(得到了a == [1, 2, 3, 4])

  • 代码运行效果截屏图片

    img

  • 将while循环条件改为a不为空,就可以达成您的预期

    img

#!/sur/bin/nve python
# coding: utf-8

def f(s):
    
    if s == []: #这一行可以写成下面的样子。
    #if not s: # “空”就是False。
        return []
    else:
        s.pop()
        return s

a = list(range(1,6))
print(f"\n列表a:{a}, Id: {id(a)}") 

while a:
    print(f"\nwhile内调用f(a)函数前返回的列表a:{a}, Id: {id(a)}")
    a = f(a)
    print(f"\nwhile内调用f(a)函数后返回的列表a:{a}, Id: {id(a)}")

print(f"\n最后列表a:{a}, Id: {id(a)}") 


第124行的 return s,往前缩进一下,和if。else对齐,在执行一下试试


如果以上回答对您有所帮助,点击一下采纳该答案~谢谢