倒计时函数只返回一个值

Countdown Function Only Returning One Value

第二个函数有什么问题?

def count(n):
  return [i for i in range (n,-1,-1)]

给我 [5, 4, 3, 2, 1] 的准确结果,但是

def count(n):
  for i in range (n,-1,-1):
      return i

总是returnsn.

正如人们在评论中所说,return 停止函数并且 returns 值。使用 generator if you want to do something like this, but not exit the function. Also, it is recommended that you use 4 spaces for indentation by PEP 8,官方 Python 风格指南。

def count(n):
    for i in range(n, -1, -1):
        yield i

print(list(count(5)))